samedi 5 avril 2014

python - ajout des valeurs d'un dictionnaire à une liste - Stack Overflow


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




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.




Several problems here:



  • wrong syntax on the pos = {1:(3,7), 2(3,0),3(2,0),4(5,8)} line, watch colons

  • indentation, the if block should be indented

  • variables in python are case-sensitive, there is no Key variable defined, you probably meant key instead


Here's the code with fixes:


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])

After running the code, h will be equal to:


[(3, 7), (3, 0), (2, 0), (5, 8)]

Hope that helps.



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



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.



Several problems here:



  • wrong syntax on the pos = {1:(3,7), 2(3,0),3(2,0),4(5,8)} line, watch colons

  • indentation, the if block should be indented

  • variables in python are case-sensitive, there is no Key variable defined, you probably meant key instead


Here's the code with fixes:


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])

After running the code, h will be equal to:


[(3, 7), (3, 0), (2, 0), (5, 8)]

Hope that helps.


0 commentaires:

Enregistrer un commentaire