2015-04-01 112 views
0

我有一个Python的字典有问题。Python字典问题更新值

import random 

values = {"A" : [2,3,4], "B" : [2], "C" : [3,4]} 


# this variable have to store as keys all the values in the lists kept by the variable values, and as values a 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 = {} 

for x in values.keys(): 
    listOfKeyX = values[x] 
    newValues = [] 
    for index in range (0, 5): 
     newValue = random.randint(0,15) 
     newValues.append(newValue) 
    for value in listOfKeyX: 
     if value in dictionary.keys(): 
      for index in range (0, 5): 
       #i want to update a value in dictionary only if the "if" condition is satisfied 
       if(newValues[index] < dictionary[value][index]): 
        dictionary[value][index] = newValues[index] 
     else: 
      dictionary.setdefault(value, []) 
      dictionary[value] = newValues 
    print dictionary 

我在尝试更改字典值时遇到问题。我只想修改通过key = value选择的对键值,但这段代码会更改所有字典值。 你能为我提出解决这个问题的解决方案吗?

我试着解释一下算法的作用: 它在值变量的键上进行迭代,并且它保留变量listOfKeyX链接到键的列表。 它创建了由newValues []保留的一些随机值。 之后它在listOfKeyX 上进行迭代,如果从列表中取得的值不存在于dictionary.keys()中,则它存储dictionaty [value]中的所有newValues列表, 如果从列表中取得的值已经存在于dictionary.keys()它需要由dictionary [value]保存的列表并尝试以某种方式升级它。

+0

这段代码究竟在干什么?什么'listValues'有'.keys'?什么是'hashFamily'? 'maxFunction'? – jonrsharpe 2015-04-01 15:03:34

+0

hashFamily它只是一个基于hashedIndex返回x的哈希值的函数,maxFunction是最大迭代次数,因此它是一个costant值。 listValues它是一个返回一组单词或数字的函数,它返回一个字典对象。 – 2015-04-01 15:11:03

+0

所以,如果它返回一个字典,为什么在它的名字是“列表”?请阅读http://stackoverflow.com/help/mcve – jonrsharpe 2015-04-01 15:11:58

回答

0

在第一循环中,在运行此代码三次:

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

这意味着,在每dictionary值是相同的列表的引用。我还没有完全确定你要找的结果是什么,但更换的各行:

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

将至少意味着它们不共享的参考。

+0

是啊!我是一名Python初学者,对此我不太了解。不过谢谢! – 2015-04-01 16:13:12