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 に答える
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 に答える