【问题标题】:Python for loop appending to every key in dictionaryPython for循环附加到字典中的每个键
【发布时间】:2016-12-12 10:59:49
【问题描述】:

我正在遍历一个元组列表和一个字符串列表。字符串是列表中项目的标识符。我有一个字典,其中包含字符串标识符作为键,并且每个值都有一个最初为空的列表。我想将元组列表中的某些内容附加到每个键。我正在做的一个简化版本是:

tupleList = [("A","a"),("B","b")]
stringList = ["Alpha", "Beta"]
dictionary = dict.fromkeys(stringList, [])  # dictionary = {'Alpha': [], 'Beta': []}
for (uppercase, lowercase), string in zip(tupleList, stringList):
    dictionary[string].append(lowercase)

我希望这会提供dictionary = {'Alpha': ['a'], 'Beta': ['b']},但我却发现{'Alpha': ['a', 'b'], 'Beta': ['a', 'b']}。有谁知道我做错了什么?

【问题讨论】:

  • 不应该小写始终是元组中的第二个项目,因为我正在匹配(大写,小写)对 tupleList?
  • 我的错,我发帖后才意识到我的错误,对不起。

标签: python list dictionary iteration


【解决方案1】:

您的问题是您通过引用共享两个键之间的列表。

发生的情况是dict.fromkeys 不会为每个键创建一个新列表,而是为所有键提供对同一列表的引用。您的其余代码看起来正确:)

你应该使用defaultdict,而不是这样做,基本上它是一个字典,如果它们不存在,它会创建新值,如果它们存在则检索它们(并且在插入时不需要 if / else检查它是否已经存在的项目)。它在这些情况下非常有用:

from collections import defaultdict

tupleList = [("A","a"),("B","b")]
stringList = ["Alpha", "Beta"]
dictionary = defaultdict(list) # Changed line
for (uppercase, lowercase), string in zip(tupleList, stringList):
    dictionary[string].append(lowercase)

【讨论】:

  • 你也可以写dictionary = defaultdict(list),而不是dictionary = defaultdict(lambda: []),我觉得这样更易读。
  • 谢谢,真的好多了:)
【解决方案2】:

问题在于,当您调用dict.fromkeys 并将列表作为每个键的默认项传递给它时,python 使用相同的列表,列表不是不可变的,因此对列表的一次更改会影响它被引用的任何地方,什么你可以做的是不带任何参数调用dict.fromkeys,这会将默认项目设置为None,然后你有一个if语句来检查它是否为None并初始化两个不同的列表。然后如果它不是 None (当它已经存在时),则随后附加到该列表。

tupleList = [("A","a"),("B","b")]
stringList = ["Alpha", "Beta"]
dictionary = dict.fromkeys(stringList)  # dictionary = {'Alpha': [], 'Beta': []}
for (uppercase, lowercase), string in zip(tupleList, stringList):
    #print(id(dictionary[string])) uncomment this with your previous code
    if dictionary[string] is None:
        dictionary[string] = [lowercase]
    else:
        dictionary[string].append(lowercase)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-02-28
    • 2016-10-14
    • 2019-07-26
    • 2021-05-19
    • 2020-03-02
    • 2019-06-14
    • 2018-12-01
    相关资源
    最近更新 更多