我有一个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
使用,但选择您需要的)。
把它变成一个函数:
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}