python - 为什么我有重复的键?

时间:2013-03-26 13:55:58

标签: python dictionary python-2.7

键是一个字符串,字典allLines的值是一个python对象列表。

original_list = allLines.get(key)
new_list = []
if original_list is not None:
    for l in original_list:
      new_list.append(l)  #add rest
new_list.append(temp) # plus new one
allLines[key] = new_list

temps是添加到列表末尾的新对象。

当我执行最后一行时,它应该完全替换original_list但是当我打印dict时,我每次运行操作时都会获得具有不同列表的重复键。什么是正确的方法呢?

我第一次运行

allLines = {"boolean mark":[obj1]}

我第二次跑步时得到:

allLines = {"boolean mark":[obj1], "boolean mark":[obj1, temp]}

而不是:

allLines = {"boolean mark":[obj1, temp]}

2 个答案:

答案 0 :(得分:1)

DATA = {"records": [{"key1": "AAA", "key2": "BBB", "key3": "CCC", "key4": "AAA"}]}

for name, datalist in DATA.iteritems():  # Or items() in Python 3.x
    for datadict in datalist:
        for key, value in datadict.items():
            if value == "AAA":
                datadict[key] = "XXX"

print (DATA)

输出:

{'records': [{'key3': 'CCC', 'key2': 'BBB', 'key1': 'XXX', 'key4': 'XXX'}]}

取自here

答案 1 :(得分:0)

我无法使用下面的代码重现您的结果。我不得不添加一些东西来制作你发布的可执行文件,但之后,它似乎做你想要的,而不是你说的发生 - 这无论如何都是不可能的,因为字典不能有重复的密钥,因为你声称是发生。这两个键必须在某种程度上有所不同,如果你能弄清楚它们之间的区别,你可以自己解决问题。

def obj(name):
    return type(name, (object,), dict(__repr__=lambda self: name))()

allLines = {}  # global var

def operation(key, temp):
    original_list = allLines.get(key)
    new_list = []
    if original_list is not None:
        for l in original_list:
            new_list.append(l)  #add rest
    new_list.append(temp) # plus new one
    allLines[key] = new_list

operation('boolean mark', obj('obj1'))
print 'allLines =', allLines
operation('boolean mark', obj('temp'))
print 'allLines =', allLines

输出:

allLines = {'boolean mark': [obj1]}
allLines = {'boolean mark': [obj1, temp]}
相关问题