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
First, a given key can appear in a dictionary only once. Duplicate keys are not allowed.
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.
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.
To determine how many items (key-value pairs) a dictionary has, use the len() method.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With