【问题标题】:Value duplicated in dictionary字典中重复的值
【发布时间】:2022-11-15 14:15:00
【问题描述】:

以下是我的代码:

test = [{'name' : 'one'}, {'name' : 'two'}]

a = {}
b = []
c = {}
for i in test:
     c['name'] = i['name']
     b.append(c)
a['items'] = b
print(a)

这会产生字典a 的以下内容,这是错误的:

{'items': [{'name': 'two'}, {'name': 'two'}]}

为什么输出字典 a 包含值 'two' 两次,而不是值 'one' 的 1 倍和值 'two' 的 1 倍?

【问题讨论】:

  • 因为是同一个对象...

标签: python list dictionary


【解决方案1】:

你只创造了dict 命名为c,所以它的name 键在每次循环中都会更改。你想要一个新的dict 每次通过循环附加到b:移动c = {}进入循环的主体。

for i in test:
    c = {}
    c['name'] = i['name']
    b.append(c)

或者

for i in test:
    c = {'name': i['name']}
    b.append(c)

或者

b = [{'name': i['name']} for i in test]

【讨论】:

  • 这确实解决了问题,但我仍然不明白为什么它应该重要,我在附加后添加了一个 print(b) 以查看发生了什么,这就是结果 [{'name': 'one'}] [{'name ': 'two'}, {'name': 'two'}] 它最初确实附加了 {'name' : 'one'} 但是在下一次迭代中改变了两个值我不明白为什么它改变了已经附加的一
  • 它首先附加了 [{'name': 'one'}] 并在第二次迭代中更改为 [{'name': 'two'}, {'name': 'two'}] 我不明白
  • b.append不加一个复制c 的列表;它只是一遍又一遍地添加相同的引用。你应该阅读nedbatchelder.com/text/names.html。 (cb[0]、b[1]等,都是指同一个对象。通过一个变量改变它,变化从全部其中。)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-02-16
  • 2019-11-13
  • 2016-10-21
  • 2020-09-04
  • 2014-11-14
  • 1970-01-01
相关资源
最近更新 更多