lundi 5 janvier 2015

Python : List as a Value in a Dictionary


I am a newbie to Python and was reading up about dictionaries from the Python Tutorial and came across the following scenario .




  • Let us say that there exists a dictionary : {'x':[0,0,70,100,...] , 'y':[0,20,...] , ...}

  • I want to systematically get hold of the value (which is a list here) for each key and then paly around with the elements of the list . Make some comparisons among the values of the list etc.

  • I wish to do this task dynamically i.e. using a loop - basically automated

  • At present I can do it statically i.e. by hard-coding it but that does not take me anywhere



This is the code that I have :



import random

def do_stuff():

NUMBER_OF_ELEMENTS = 5

list_of_pokemon = ['pikachu', 'charizard', 'sabertooth' , 'raichu']

dict_of_pokemon = {}

for i in list_of_pokemon:
dict_of_pokemon[i] = [random.randrange(0, 200,10) for j in range(NUMBER_OF_ELEMENTS)]


#This just prints out a dict of the form : {'pikachu':[200,50,40,60,70] , .....}
print dict_of_pokemon

dict_of_changes = {}

temp = []

for x in dict_of_pokemon:

for y in dict_of_pokemon[x]:
# I wish to compare the elements of a value list
# For example : pairwise comparing (200,50);(50,40);(40,60);(60,70)


My Doubt:


Can Someone help me out ?


This is not a homework question.





Aucun commentaire:

Enregistrer un commentaire