Python for循环附加到字典中的每个键

Ben*_*ett 3 python iteration dictionary list

我正在迭代一个元组列表和一个字符串列表.字符串是列表中项目的标识符.我有一个字典,其字符串标识符为键,并且每个值都有一个最初为空的列表.我想从元组列表中向每个键添加一些内容.我正在做的简化版本是:

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)
Run Code Online (Sandbox Code Playgroud)

我希望这能给予dictionary = {'Alpha': ['a'], 'Beta': ['b']},但我找到了{'Alpha': ['a', 'b'], 'Beta': ['a', 'b']}.有谁知道我做错了什么?

Ehu*_*ish 5

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

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

你应该使用defaultdict而不是你应该使用defaultdict,它基本上是一个dict,如果它们不存在就会创建新值,如果它们存在则会检索它们(并且在插入项目时不需要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)
Run Code Online (Sandbox Code Playgroud)

  • 而不是`dictionary = defaultdict(lambda:[])`你也可以写`dictionary = defaultdict(list)`,我发现它更具可读性. (2认同)