atlas cube atlas cube - 1 year ago 60
Python Question

Comparing list with dictionary to make new list in python

I have one list and one dictionary. I want to compare the list values with the keys of the dictionary. If I have:

mydict = {'Hello':1,'Hi':2,'Hey':3}


mylist = ['Hey','What\'s up','Hello']

I want the output to be:

output = [3, None, 1]


I tried
[mydict[i] for i in mylist]
and I get an error instead of None. I then tried using nested for loops (I deleted that bit) but I decided that was to inefficient.

Answer Source

Use a list comprehension:

output = [ mydict.get(key) for key in mylist ]

Note that dict.get returns None if the key is not in the dict.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download