How to extract only certain values from a dictionary (python)

Viewed 10231

Let's say that I have a list l=[1, 2, 3, 4] and a dictionary d={2:a, 4:b}. I'd like to extract the values of d only in the key is also in my list and put the result in a new list. This is what I've tried so far:

new_l=[]
for i in l:
    for key in d.keys():
        if key in l:
            new_l.append(d[key])
print (new_l)

Thank you in advance for your help.

4 Answers

This will compare each value in the dictionary and if it's match in the list.

Simplistic answer..

>>> l
[1, 2, 3, 4]

>>> d
{2: 'a', 4: 'b'}

>>> [value for (key,value) in d.items() if key in l] 
['a', 'b']

You don't need to cycle through each key in that second for loop. With Python, you can just use a list comprehension:

L = [1, 2, 3, 4]
d = {2: 'a', 4: 'b'}

res = [d[i] for i in L if i in d]   # ['a', 'b']

An alternative functional solution is possible if you know your dictionary values are non-Falsy (e.g. not 0, None). filter is a lazy iterator, so you'll need to exhaust via list in a subsequent step:

res = filter(None, map(d.get, L))

print(list(res))  # ['a', 'b']

You can skip iterating l

Ex:

l=[1, 2, 3, 4] 
d={2:"a", 4:"b"}


new_l=[]
for key in d.keys():
    if key in l:
        new_l.append(d[key])
print (new_l)

Iterate the dictionary with key and match the key present in list.

L=[1, 2, 3, 4] 
d={2:"a", 4:"b"}

new_l=[]
for k in d.keys():
    if k in L:
        new_l.append(d[k])
print (new_l)
Related