atlas cube atlas cube - 3 months ago 8
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}


and:

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


I want the output to be:

output = [3, None, 1]


Thanks!

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

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.