私はdictionary
次のようなものを持っています:
{'items': [{'id': 1}, {'id': 2}, {'id': 3}]}
で内部辞書を直接取得する方法を探していid = 1
ます。
list
アイテムをループして比較する以外に、これに到達する方法はありid
ますか?
私はdictionary
次のようなものを持っています:
{'items': [{'id': 1}, {'id': 2}, {'id': 3}]}
で内部辞書を直接取得する方法を探していid = 1
ます。
list
アイテムをループして比較する以外に、これに到達する方法はありid
ますか?
first_with_id_or_none = \
next((value for value in dictionary['items'] if value['id'] == 1), None)
それを関数にします:
def get_inner_dict_with_value(D, key, value):
for k, v in D.items():
for d in v:
if d.get(key) == value:
return d
else:
raise ValueError('the dictionary was not found')
説明付き:
def get_inner_dict_with_value(D, key, value):
for k, v in D.items(): # loop the dictionary
# k = 'items'
# v = [{'id': 1}, {'id': 2}, {'id': 3}]
for d in v: # gets each inner dictionary
if d.get(key) == value: # find what you look for
return d # return it
else: # none of the inner dictionaries had what you wanted
raise ValueError('the dictionary was not found') # oh no!
それを実行する:
>>> get_inner_dict_with_value({'items': [{'id': 1}, {'id': 2}, {'id': 3}]}, 'id', 1)
{'id': 1}
別の方法:
def get_inner_dict_with_value2(D, key, value):
try:
return next((d for l in D.values() for d in l if d.get(key) == value))
except StopIteration:
raise ValueError('the dictionary was not found')
>>> get_inner_dict_with_value2({'items': [{'id': 1}, {'id': 2}, {'id': 3}]}, 'id', 1)
{'id': 1}