简体   繁体   中英

Adding the values of a dictionary to a list

Hi I am having a bit of difficulty adding tuples which are the values of a dictionary I have extracted the tuples and need to added to an iterable item say an empty list. ie

path = [1,2,3,4]
pos = {1:(3,7), 2(3,0),3(2,0),4(5,8)}
h = []
for key in path:
     if key in pos:
     print pos[key]
     h.append(pos[Key])#Gives an error

Please how can i append the values in pos[key] into a h. Thanks

You can use list comprehension :

h = [pos[key] for key in path if key in pos]

Demo:

print h
>>> [(3, 7), (3, 0), (2, 0), (5, 8)]

Notes:

  • A dictionary should be declared like pairs of key:value . Your syntax is incorrect.
  • Also, Python is case-sensitive so key is different than Key .

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