Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to filter a dict to contain only keys in a given list? [duplicate]

Both very new to Python and stackoverflow. Thank you for your patience, and your help.

I would like to filter a dict according to the content of a list like this:

d={'d1':1, 'd2':2, 'd3':3}

f = ['d1', 'd3']

r = {items of d where the key is in f}

Is this absurd? If not, what would be the right syntax?

Thank you for your help.

Vincent

like image 883
Vincent Avatar asked Jul 26 '11 09:07

Vincent


People also ask

Can dictionary contains duplicate keys?

First, a given key can appear in a dictionary only once. Duplicate keys are not allowed.

How do dictionary handle duplicate keys?

If you want to keep duplicate keys in a dictionary, you have two or more different values that you want to associate with same key in dictionary. The dictionary can not have the same keys, but we can achieve a similar effect by keeping multiple values for a key in the dictionary.

How do you filter data in a dictionary Python?

Filter a Dictionary by filter() Instead of creating our own function we can also use python's filter() function too. filter() function accepts a, an iterable sequence to be filtered. a function that accepts an argument and returns bool i.e. True or False based on it's logic.

Does dict have Len?

To determine how many items (key-value pairs) a dictionary has, use the len() method.


2 Answers

You can iterate over the list with a list comprehension and look up the keys in the dictionary, e.g.

aa = [d[k] for k in f]

Here's an example of it working.

>>> d = {'k1': 1, 'k2': 2, 'k3' :3}
>>> f = ['k1', 'k2']
>>> aa = [d[k] for k in f]
>>> aa
[1, 2]

If you want to reconstruct a dictionary from the result, you can capture the keys as well in a list of tuples and convert to a dict, e.g.

aa = dict ([(k, d[k]) for k in f])

More recent versions of Python (specifically 2.7, 3) have a feature called a dict comprehension, which will do it all in one hit. Discussed in more depth here.

like image 71
ConcernedOfTunbridgeWells Avatar answered Sep 30 '22 10:09

ConcernedOfTunbridgeWells


Assuming you want to create a new dictionary (for whatever reason):

d = {'d1':1, 'd2':2, 'd3':3}
keys = ['d1', 'd3']

filtered_d = dict((k, d[k]) for k in keys if k in d)
# or: filtered_d = dict((k, d[k]) for k in keys)
# if every key in the list exists in the dictionary
like image 39
Felix Kling Avatar answered Sep 30 '22 10:09

Felix Kling