简体   繁体   中英

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.

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.

Use dict.get() , which defaults to None if key does not exist:

[mydict.get(k) for k in mylist]

>>> mydict = {'Hello':1,'Hi':2,'Hey':3}
>>> mylist = ['Hey','What\'s up','Hello']
>>> out = [mydict.get(k) for k in mylist]
>>> out
[3, None, 1]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM