如何为列表中的每个字典替换字典值,这是字典与元组

时间:2018-02-23 18:50:56

标签: python dictionary

  

错误'tuple'对象没有属性'items'

当我试图替换最后一行代码中的字典值时,但不在循环中它可以工作(3行代码)。

dictionary = { "a" : "100", "b" : "200", "c" : {"a":"f","b":"4"} }
D = [dictionary for i in range(10)]
#dictionary["c"] = tuple(dictionary["c"].items()) # it works
for i in D:
    i["c"] = tuple(i["c"].items()) # does not work

1 个答案:

答案 0 :(得分:1)

这不起作用,因为当你这样做时:

D = [dictionary for i in range(10)]

您创建一个列表,其中包含对同一对象的10个引用。第一次迭代成功完成后:

i['c'] = tuple(i['c'].items())

下一个保证失败,因为它是你在上一次迭代中处理的同一个对象,所以'c'值是tuple

注意:

In [10]: dictionary = { "a" : "100", "b" : "200", "c" : {"a":"f","b":"4"} }
    ...: D = [dictionary for i in range(10)]
    ...: print([hex(id(x)) for x in D])
    ...:
['0x105c59088', '0x105c59088', '0x105c59088', '0x105c59088', '0x105c59088', '0x105c59088', '0x105c59088', '0x105c59088', '0x105c59088', '0x105c59088']

相反,做一些事情:

In [11]: dictionary = { "a" : "100", "b" : "200", "c" : {"a":"f","b":"4"} }
    ...: D = [dictionary.copy() for i in range(10)]
    ...: print([hex(id(x)) for x in D])
    ...:
['0x105c592c8', '0x105c59e48', '0x105cfd848', '0x105c9af48', '0x105d06c48', '0x105c59708', '0x105d06cc8', '0x105c59488', '0x105c59e08', '0x105c593c8']

现在它会起作用:

In [12]: for i in D:
    ...:     i['c'] = tuple(i['c'].items())
    ...:

In [13]: D
Out[13]:
[{'a': '100', 'b': '200', 'c': (('b', '4'), ('a', 'f'))},
 {'a': '100', 'b': '200', 'c': (('b', '4'), ('a', 'f'))},
 {'a': '100', 'b': '200', 'c': (('b', '4'), ('a', 'f'))},
 {'a': '100', 'b': '200', 'c': (('b', '4'), ('a', 'f'))},
 {'a': '100', 'b': '200', 'c': (('b', '4'), ('a', 'f'))},
 {'a': '100', 'b': '200', 'c': (('b', '4'), ('a', 'f'))},
 {'a': '100', 'b': '200', 'c': (('b', '4'), ('a', 'f'))},
 {'a': '100', 'b': '200', 'c': (('b', '4'), ('a', 'f'))},
 {'a': '100', 'b': '200', 'c': (('b', '4'), ('a', 'f'))},
 {'a': '100', 'b': '200', 'c': (('b', '4'), ('a', 'f'))}]