【问题标题】:Python Dictionary append value errorPython字典追加值错误
【发布时间】:2017-05-06 14:38:59
【问题描述】:

我试图将一个值(列表)附加到字典中,但没有成功。通过 'equal' 设置值有效,但附加无效。

DurationDict = dict()
DurationDict[str(curYear)] = duration  // This works
DurationDict[str(curYear)].append(duration) //This does't work.

有什么想法吗?

【问题讨论】:

  • 您可以将append 发送至list,但不能发送至dict。这是python doc for dictionaries。
  • 如果值是列表类型,您只能附加到键的值。
  • 你的代码等于“duration.append(duration)”,你应该确保duration是一个列表
  • 那么,在您提出这个问题之前,您甚至没有尝试检查文档?

标签: python dictionary append


【解决方案1】:

您可以附加到list,但不能附加到dict。 python dicts 是documented here。

如果您想为所有字典条目设置list,可以使用defaultdict:

collections import defaultdict

DurationDict = defaultdict(list)
DurationDict[str(curYear)].append(duration)

defaultdict 像普通的dict 一样工作,只是它返回“工厂”的结果 - 在这种情况下,list() 如果您正在查找的密钥尚不存在。然后你可以追加到这个(空)列表中。

【讨论】:

  • 如果您向 OP 解释为什么他们的尝试没有奏效,以及为什么这可以解决他们的问题(因为这是 OP 问题的正确解决方案,我相信),这个答案将会大大改善。
  • @SethMMorton:好点。添加了一个简短的解释。为什么 OP 的方法不起作用是我对帖子的第一条评论。
【解决方案2】:

如果要附加到字典的值,那么值应该是list的类型。

让我们考虑以下示例:

>>> k = {"a":1}
>>> k["b"] = 2
>>> k["c"] = [2]
>>> k["c"].append("new value") # here you can append because value of c is type of list.
>>> print(k)
{'a': 1, 'c': [2, 'new value'], 'b': 2}
>>> k["b"].append("new value") # here you can not append because value of b is type of int 

【讨论】:

    【解决方案3】:

    您只能附加lists。如果你有一个空字典d,

    d = {} # initialize an empty dictionary
    d['a'].append(1) # will NOT work
    

    但是如果你已经定义了一个空的list,

    d = {'a': []} # initialize with an empty list
    df['a'].append(1) # will work
    
    >>> d
    {'a': [1]}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-03-10
      • 2021-01-07
      • 1970-01-01
      • 1970-01-01
      • 2015-02-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多