【问题标题】:Loop over 2 dictionnaries and append several values to a key循环遍历 2 个字典并将多个值附加到一个键
【发布时间】:2021-10-26 16:11:00
【问题描述】:

我有两个词典,第一个是展示一些作品:

d= {"a": "pompier", "b": "policier", "c": "tracteur"}

第二个是与列表类型的作品相关的形容词

d1 = {"a": "[gentil, fort]", "b": "[juste, amicale]", "c": "[fonctionnel, fort, utile]"}

我想将 d1 字典中的值附加到 d 字典中,使其看起来像这样

d2 = {"a": "pompier", "[gentil, fort]", "b": "policier", "[juste, amicale]", "c": "tracteur", "[fonctionnel, fort, utile]"}

我需要精确,我不知道(在我的原始文件中)是否存在 d1 中不在 d 字典中的键...

我试过这段代码,但它返回错误

or key, value in d.items():
for key1, value1 in d1.items():
    if key in d1:
        d1[key].append[value1]
    print(d1)

    Traceback (most recent call last):
  File "<string>", line 7, in <module>
AttributeError: 'str' object has no attribute 'append'

提前谢谢你

【问题讨论】:

  • 你的字典 d2 无法定义,你应该重新检查你真正想要的输出
  • 你还没有说在 d1 中的键在 d 中不存在的情况下你想要什么行为。举个例子会更清楚。

标签: python loops dictionary


【解决方案1】:
d= {"a": "pompier", "b": "policier", "c": "tracteur"}
d1 = {"a": "[gentil, fort]", "b": "[juste, amicale]", "c": "[fonctionnel, fort, utile]"}
d2 = dict()
for key, value in d.items():
    if d1.get(key):
        d2[key] = [value, d1.get(key)]
    else:
        d2[key] = value

print(d2)

首先,你需要定义d2。其次,你有字符串,而不是列表,所以你不能使用 append。相反,您必须将它们添加到列表中。在这里,如果一个键在 d1 中不存在,它将只保留一个值,如果存在,它会将它们添加到列表中。

这里有 2 个选项。如果您希望值始终在列表中,只需输入d2[key] = [value]

如果您在 d1 中有键在 d 中不存在,您应该通过 d1.items() 进行另一个循环并仅添加缺少的键:

for key, value in d1.items():
    if key not in d.keys():
        d2[key] = value

【讨论】:

  • defaultdict 有助于避免所有这些额外检查。
  • 我认为现有形式的问题对于else 块中的确切内容还不够清楚。我已要求澄清。
猜你喜欢
  • 1970-01-01
  • 2019-08-19
  • 2013-07-02
  • 1970-01-01
  • 2019-09-02
  • 1970-01-01
  • 2017-12-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多