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

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

I would like to filter the dict according to the contents of the list:

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 will be the correct syntax?

Thank you for your help.

Vincent

+6
source share
2 answers

Assuming you want to create a new dictionary (for any 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 
+13
source

You can iterate over a list with a list and look for keys in a dictionary, for example

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

Here is an example of his work.

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

If you want to restore the dictionary from the result, you can also grab the keys in the list of tuples and convert to dict, for example.

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

In later versions of Python (in particular, 2.7, 3) there is a function called the concept of dict, which will do it all in one hit. Discussed in more detail here.

+3
source

Source: https://habr.com/ru/post/893573/


All Articles