Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
458 views
in Technique[技术] by (71.8m points)

python - Filter a dict of dict

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...