Python dictionary issue update values -


i've problem python's dictionary.

import random  values = {"a" : [2,3,4], "b" : [2], "c" : [3,4]}   # variable have store keys values in lists kept variable values, , values list of numbers # example of dictionary : # {"2" : [2, 6 ,7 ,8, 8], "3" : [9, 7, 6, 5, 4], "4" : [9, 7, 5, 4, 3]} dictionary = {}  x in values.keys():     listofkeyx = values[x]     newvalues = []     index in range (0, 5):         newvalue = random.randint(0,15)         newvalues.append(newvalue)     value in listofkeyx:         if value in dictionary.keys():             index in range (0, 5):                 #i want update value in dictionary if "if" condition satisfied                 if(newvalues[index] < dictionary[value][index]):                     dictionary[value][index] = newvalues[index]         else:             dictionary.setdefault(value, [])             dictionary[value] = newvalues     print dictionary 

i have problem dictionary values when i'm trying change them. want modify pairs key-value selected through key = value piece of code changes dictionary values. can suggest me solution issue?

i try explain algorithm does: iterates on keys of values variable , keeps in variable listofkeyx list linked key. creates random values kept newvalues[]. after iterates on listofkeyx if value taken list not exists in dictionary.keys() stores newvalues list in dictionaty[value], if value taken list exists in dictionary.keys() takes list kept dictionary[value] , tries upgrade in way.

in first loop, run code 3 times:

dictionary.setdefault(value, [])  # create brand new list dictionary[value] = newvalues  # ignore , use newvalues 

this means every value in dictionary reference same list. i'm still not totally sure outcome you're looking is, replacing lines above with:

dictionary[value] = newvalues[:]  # shallow copy creates new list 

will @ least mean don't share reference.


Comments

Popular posts from this blog

How to run C# code using mono without Xamarin in Android? -

c# - SharpSsh Command Execution -

python - Specify path of savefig with pylab or matplotlib -