按键在字典列表中到达字典

时间:2013-06-27 14:51:25

标签: python dictionary

我的dictionary看起来像这样:

{'items': [{'id': 1}, {'id': 2}, {'id': 3}]}

我正在寻找一种用id = 1直接获取内部字典的方法。

除了循环list项并比较id之外,还有其他办法吗?

3 个答案:

答案 0 :(得分:3)

first_with_id_or_none = \
    next((value for value in dictionary['items'] if value['id'] == 1), None)

答案 1 :(得分:3)

您将 循环遍历列表。好消息是你可以使用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,但选择您需要的内容。)

答案 2 :(得分:2)

将它变成一个函数:

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}
相关问题