これはfilter
を用いた一般的なソリューションです。内蔵の方法は、あなたのニーズにそれを採用する必要があります:
>>> list(filter(lambda d: d['b'] in lst, dic['info']))
[{'b': '1', 'a': 0}, {'b': '1', 'a': 0}]
がlist
コンストラクタを使用して、リストへfilter
オブジェクトを変換Python2で、それが必要とされていないのに対し、唯一のpython3に必要です:
>>> filter(lambda d: d['b'] in lst, dic['info'])
[{'b': '1', 'a': 0}, {'b': '1', 'a': 0}]
EDIT:その後、次のことを考慮し、lst
場合、複数の項目にはソリューションは、より一般的にするには:
>>> dic
{'info': [{'b': '1', 'a': 0}, {'b': '3', 'a': 0}, {'b': '3', 'a': 0}, {'b': '1', 'a': 0}, {'b': '2', 'a': '1'}]}
>>>
>>> lst
['1', '2']
>>> def filter_dict(dic_lst, lst):
lst_out = []
for sub_d in dic_lst:
if any(x == sub_d['b'] for x in lst):
lst_out.append(sub_d)
return lst_out
>>> filter_dict(dic['info'], lst)
[{'b': '1', 'a': 0}, {'b': '1', 'a': 0}, {'b': '2', 'a': '1'}]
OR:
>>> list(map(lambda x: list(filter(lambda d: d['b'] in x, dic['info'])),lst))
[[{'b': '1', 'a': 0}, {'b': '1', 'a': 0}], [{'b': '2', 'a': '1'}]]
リストは常に1つのアイテムを持っているのだろうか?このアイテムは常にキー「b」の値ですか?期待される出力はリストかタプルであるはずですか? 'info'は辞書' dic'の唯一の鍵でしょうか?これらの質問に対する答えがすべて「はい」の場合、Kasramvdの回答は得られるほど良好です。 –
なぜそれが下降しているのだろう... –