简体   繁体   中英

How to append to a list using list comprehension and dict keys

I have an empty list and a dictionary

subject = []
dict = {'1' : 'Test', '2':'Assignments', '3':'Homeworks', etc.}

I have another list that is user generated

start_prompt = ['1', '2', '5']

I want to go through go through the list start_prompt and use it as the key to append the dict values to the empty list subject. This is what I tried doing, but it doesn't work

x = [subject.append(dict[i]) for i in start_prompt]

Am I missing something really obvious, or is this not the proper way to do it?

I would do the following, and also check that that key exists in your dictionary.

d = {'1' : 'Test', '2':'Assignments', '3':'Homeworks'}
start_prompt = ['1', '2', '5']
subject = [d[i] for i in start_prompt if i in d]

>>> subject
['Test', 'Assignments']

PS Do not use the type name as your variable! (Do not name your dictionary dict )

I prefer the other answer but for variation

d = {'1' : 'Test', '2':'Assignments', '3':'Homeworks'}
start_prompt = ['1', '2', '5']
from operator import itemgetter
itemgetter(*d.viewkeys() & start_prompt)(d)
('Test', 'Assignments')
list(itemgetter(*d.viewkeys() & start_prompt)(d))
['Test', 'Assignments']

Not that i recommend it

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