2

我有一个dictionary看起来像这样的:

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

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

list除了循环项目和比较之外,有没有办法达到这个目的id

4

3 回答 3

3
first_with_id_or_none = \
    next((value for value in dictionary['items'] if value['id'] == 1), None)
于 2013-06-27T14:53:33.140 回答
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使用,但选择您需要的)。

于 2013-06-27T14:53:37.863 回答
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}
于 2013-06-27T15:02:37.193 回答