【问题标题】:python appending a dictonary to list is changing all the list elements [duplicate]python将字典附加到列表正在更改所有列表元素[重复]
【发布时间】:2014-02-25 10:51:00
【问题描述】:

我要列表d = [{'name': 'Ada Lovelace'},{'name': 'Alan Turing'}]

但是字典变异了

    >>> a = ['Ada Lovelace','Alan Turing']
    >>> c = dict()
    >>> d = []
    >>> for i in a:
    ...    print c
    ...    print d
    ...    c['name'] = i
    ...    d.append(c)
    ...    print c
    ...    print d
    ... 
    {}
    []
    {'name': 'Ada Lovelace'}
    [{'name': 'Ada Lovelace'}]
    {'name': 'Ada Lovelace'}
    [{'name': 'Ada Lovelace'}]
    {'name': 'Alan Turing'}
    [{'name': 'Alan Turing'}, {'name': 'Alan Turing'}]

【问题讨论】:

  • 因为您将相同的字典对象附加到列表中。更好地在循环本身中创建字典。

标签: python


【解决方案1】:

您一遍又一遍地重复使用同一个字典。在循环中创建一个 new 字典:

for i in a:
    c = {'name': i}
    d.append(c)

将对象添加到列表中不会创建副本;它只是在列表中存储对该对象的引用。

通过一遍又一遍地重复使用相同的 dict 对象,您只是将多个对 one 字典的引用附加到列表中。

【讨论】:

    【解决方案2】:

    使用字典文字语法和列表推导可以满足您的需求:

    >>> names = ['foo','bar']
    >>> d = [{'name': i} for i in names]
    >>> d
    [{'name': 'foo'}, {'name': 'bar'}]
    

    【讨论】:

      猜你喜欢
      • 2016-01-21
      • 1970-01-01
      • 2017-04-16
      • 1970-01-01
      • 1970-01-01
      • 2014-12-09
      • 2020-10-14
      • 1970-01-01
      • 2019-11-07
      相关资源
      最近更新 更多