Dictate filtering dict

I am new to Python and I'm not sure if it is a good idea to use dict of dict, but here is my question. I have a dict dict, and I want to filter the key inside a 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 example, I want the filter "id1" to have:

result = { 'key1' : {'id1' :[0,1,2] }
           'key3' : {'id1' :[4,5,6]}
         }

I tried the filter method, getting the whole value:

r = [('key1' ,{'id1' :[0,1,2] , 'id2' :[0,1,2], 'id3' :[4,5,6]})
     ('key3' , {'id3' :[0,1,2] , 'id1' :[4,5,6]})
   ]

In addition, the filter method returns a list, and I want to save the format as a dict.

Thanks in advance

+3
source share
4 answers

Try the following:

>>> { 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 can use iteritems()instead items(), and you still need the fairly recent python (2.7, I think) to understand the dictionary: 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, I think that it is best for you to write the loops 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

:

>>> query(a, ('id1', 'id2'))
{'key3': {'id1': [4, 5, 6]}, 'key1': {'id2': [0, 1, 2], 'id1': [0, 1, 2]}}
+5

, Duncan, :

>>> my_list = ['id1', 'id2']
>>> {k1 : {k2: v2 for (k2, v2) in a[k1].iteritems() if k2 in my_list} for k1 in a}
{'key3': {'id1': [4, 5, 6]}, 'key2': {}, 'key1': {'id2': [0, 1, 2], 'id1': [0, 1, 2]}}

EDIT: , "" ...: -)

>>> {k3: v3 for k3, v3 in {k1 : {k2: v2 for (k2, v2) in a[k1].iteritems() if k2 in my_list} for k1 in a}.iteritems() if v3}
{'key3': {'id1': [4, 5, 6]}, 'key1': {'id2': [0, 1, 2], 'id1': [0, 1, 2]}}
+2

You can do with a dictionary understanding:

def query(data, query):
    return {key : {query : data[key][query]} 
            for key in data if query in data[key]}

You should look at each entry in the dictionary, which can cost a lot of time if you have a lot of entries or something to do. A database with an index can speed this up.

+1
source
field = 'id1'
dict( (k,{field: d[field]}) for k,d in a.items() if field in d)
+1
source

All Articles