Python 按键访问字典列表中的字典

Python 按键访问字典列表中的字典,python,dictionary,Python,Dictionary,我有一本字典,看起来像这样: {'items': [{'id': 1}, {'id': 2}, {'id': 3}]} 我正在寻找一种方法,用id=1直接获取内部字典 除了循环列表项目并比较id之外,是否还有其他方法可以达到此目的?您必须循环列表。好消息是,您可以使用带有next()的生成器表达式来执行循环: first_with_id_or_none = \ next((value for value in dictionary['items'] if value['id'] ==

我有一本
字典
,看起来像这样:

{'items': [{'id': 1}, {'id': 2}, {'id': 3}]}
我正在寻找一种方法,用
id=1
直接获取内部字典

除了循环
列表
项目并比较
id
之外,是否还有其他方法可以达到此目的?

您必须循环列表。好消息是,您可以使用带有
next()
的生成器表达式来执行循环:

first_with_id_or_none = \
    next((value for value in dictionary['items'] if value['id'] == 1), None)
yourdict = next(d for d in somedict['items'] if d['id'] == 1)
如果没有这样的匹配字典,这会引发
StopIteration
异常

使用


为该边缘案例返回默认值(此处使用
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}

这可能是有效的javascript,但python字典键必须被引用感谢注释!编辑
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}