簡體   English   中英

如何用列表中的每個字典的元組替換字典值

[英]How to replace dictionary values which is dictionary with tuple for each dictionary in list

錯誤“元組”對象沒有屬性“項目”

當我試圖在最后一行代碼中替換字典值時,但不在循環中它起作用(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

這不起作用,因為當你這樣做時:

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'))}]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM