到達詞典列表內的字典我有一個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)
您將有通過列表循環。好消息是,是,你可以使用一個發電機表達next()
做循環:
yourdict = next(d for d in somedict['items'] if d['id'] == 1)
這可以養StopIteration
異常,如果沒有這樣的匹配字典。
使用
yourdict = next((d for d in somedict['items'] if d['id'] == 1), None)
返回缺省的,而不是針對邊緣的情況下(這裏使用None
,但挑你的需要)。
非常感謝您的幫助! – Kreutzer
使之成爲一個功能:
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}
非常感謝@Inbar – Kreutzer
這可能是有效的JavaScript,但必須引用Python字典鍵 – Eric
感謝您的評論!編輯 – Kreutzer