过滤 dict 的 dict [英] Filter a dict of dict
问题描述
我是 Python 新手,我不确定使用 dict 的 dict 是个好主意,但这是我的问题.我有一个 dict 的 dict,我想通过内部 dict 的键进行过滤:
a ={ 'key1' : {'id1' :[0,1,2] , 'id2' :[0,1,2], 'id3' :[4,5,6]}'key2' : {'id3' :[0,1,2] , 'id4' :[0,1,2]}'key3' : {'id3' :[0,1,2] , 'id1' :[4,5,6]}}
例如,我想通过id1"过滤:
result = { 'key1' : {'id1' :[0,1,2] }'key3' : {'id1' :[4,5,6]}}
我通过获取所有值尝试了过滤方法:
r = [('key1' ,{'id1' :[0,1,2] , 'id2' :[0,1,2], 'id3' :[4,5,6]})('key3' , {'id3' :[0,1,2] , 'id1' :[4,5,6]})]
此外,过滤器方法返回一个列表,我想将格式保留为字典.
提前致谢
试试这个:
<预><代码>>>>{ k: v['id1'] for k,v in a.items() if 'id1' in v }{'key3': [4, 5, 6], 'key1': [0, 1, 2]}对于 Python 2.x,您可能更喜欢使用 iteritems()
而不是 items()
并且您仍然需要一个相当新的 Python(我认为是 2.7)对于字典理解:对于较旧的 python 使用:
dict((k, v['id1']) for k,v in a.iteritems() if 'id1' in v )
如果你想提取多个值,那么我认为你最好完整地写出循环:
def 查询(数据,想要):结果 = {}对于 k, v 在 data.items():v2 = { k2:v[k2] for k2 in want if k2 in v }如果 v2:结果[k] = v2返回结果
给予:
<预><代码>>>>查询(一,('id1','id2')){'key3': {'id1': [4, 5, 6]}, 'key1': {'id2': [0, 1, 2], 'id1': [0, 1, 2]}}I new in Python and I am not sure it is a good idea to use dict of dict but here is my question. I have a dict of dict and I want to filter by the key of the inside dict:
a ={ 'key1' : {'id1' :[0,1,2] , 'id2' :[0,1,2], 'id3' :[4,5,6]}
'key2' : {'id3' :[0,1,2] , 'id4' :[0,1,2]}
'key3' : {'id3' :[0,1,2] , 'id1' :[4,5,6]}
}
For exemple , I want to filter by 'id1' to have :
result = { 'key1' : {'id1' :[0,1,2] }
'key3' : {'id1' :[4,5,6]}
}
I have tried the filter method by I get all the value:
r = [('key1' ,{'id1' :[0,1,2] , 'id2' :[0,1,2], 'id3' :[4,5,6]})
('key3' , {'id3' :[0,1,2] , 'id1' :[4,5,6]})
]
Furthermore the filter method returns a list and I want to keep the format as a dict.
Thanks in advance
Try this:
>>> { k: v['id1'] for k,v in a.items() if 'id1' in v }
{'key3': [4, 5, 6], 'key1': [0, 1, 2]}
For Python 2.x you might prefer to use iteritems()
instead of items()
and you'll still need a pretty recent python (2.7 I think) for a dictionary comprehension: for older pythons use:
dict((k, v['id1']) for k,v in a.iteritems() if 'id1' in v )
If you want to extract multiple values then I think you are best to just write the loops out in full:
def query(data, wanted):
result = {}
for k, v in data.items():
v2 = { k2:v[k2] for k2 in wanted if k2 in v }
if v2:
result[k] = v2
return result
giving:
>>> query(a, ('id1', 'id2'))
{'key3': {'id1': [4, 5, 6]}, 'key1': {'id2': [0, 1, 2], 'id1': [0, 1, 2]}}
这篇关于过滤 dict 的 dict的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!