过滤一个dict的dict [英] Filter a dict of dict

查看:237
本文介绍了过滤一个dict的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'to have:

  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]})
]

此外,filter方法返回一个列表,我想保留格式为dict。



提前感谢

解决方案

尝试这样:

 >>>对于k,v ['id1'] for a.items()if'id1'in v} 
{'key3':[4,5,6],'key1':[0, 1,2]}

对于Python 2.x,您可能更喜欢使用 iteritems()而不是 items(),你仍然需要一个漂亮的最近的python(2.7我认为)一个字典理解: pythons使用:

  dict((k,v ['id1'])for k,v in a.iteritems()if 'id1'in v)

如果你想提取多个值,那么我认为你最好只是写完循环:

  def query(data,wanted):
result = {}
for k,v in data.items():
v2 = {k2:v [k2]对于k2,如果k2在v中}
如果v2:
result [k] = v2
返回结果

给:

 >>> query(a,('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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆