Nobi
Nobi

Reputation: 1109

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. i.e.

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

Upvotes: 0

Views: 85

Answers (1)

Christian Tapia
Christian Tapia

Reputation: 34146

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.

Upvotes: 3

Related Questions