Python字典问题更新值

2024-10-02 16:31:06 发布

您现在位置: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选择的pairs键值,但是这段代码更改了所有字典值。 你能给我一个解决这个问题的办法吗?在

我试图解释该算法的作用: 它迭代values变量的键,并在变量listOfKeyX中保存链接到key的列表。 它创建一些由newValues[]保存的随机值。 之后,它在keyx的列表上迭代 如果从列表中获取的值不存在于字典.keys()它以dictionary[value]存储所有newValues列表, 如果从列表中获取的值已存在于字典.keys()它获取字典[value]保存的列表,并尝试以某种方式对其进行升级。在


Tags: thein列表forindexdictionaryif字典
1条回答
网友
1楼 · 发布于 2024-10-02 16:31:06

在第一个循环中,运行以下代码三次:

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

这意味着dictionary中的每个值都是对同一列表的引用。我仍然不完全确定您要寻找的结果是什么,但是将上面的行替换为:

^{pr2}$

至少意味着他们不共享参考资料。在

相关问题 更多 >