prof
prof

Reputation: 61

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

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.

Upvotes: 5

Views: 13927

Answers (4)

Anoop Kumar
Anoop Kumar

Reputation: 912

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)

Upvotes: 0

jpp
jpp

Reputation: 164773

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']

Upvotes: 3

Karn Kumar
Karn Kumar

Reputation: 8826

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']

Upvotes: 8

Rakesh
Rakesh

Reputation: 82785

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)

Upvotes: 0

Related Questions