如何在具有特定键的字典中添加多个值 [英] How to add multiple values in dictionary having specific key
问题描述
例如,我想为特定键添加更多值,认为我的字典是 FinalData = {}
它包含以下键值对: {'12345,70':xyz,'12345,71':pqr}
现在我想为相同的键'12345,70'添加值('abc'),以便我的最终字典成为 {'12345,70':xyz,abc,'12345,71':pqr}
我试图通过 FinalData [key] .append(value)<附加第二个值/code>却给了我
I want to add more values to specific key for example,
consider my dictionary is FinalData = {}
and it contains key value pair as: {'12345,70':xyz,'12345,71':pqr}
and now I want to add value ('abc') for same key '12345,70'so that
my final dictionary becomes {'12345,70':xyz,abc,'12345,71':pqr}
I tried to append second value by FinalData[key].append(value)
but it gives me
错误:AttributeError:'str'对象没有属性'append'
error: AttributeError: 'str' object has no attribute 'append'
那么他们有什么办法解决这个问题,我是python新手,请帮忙.
So is their any way to resolve this, I'm new to python please help.
推荐答案
使用列表而不是字符串:
Use a list instead of a string:
FinalData = {'12345,70': ['xyz'], '12345,71': ['pqr']}
这可行:
FinalData[key].append(value)
示例
key = '12345,70'
value = 'abc'
FinalData[key].append(value)
print(FinalData)
输出:
{'12345,70': ['xyz', 'abc'], '12345,71': ['pqr']}
这篇关于如何在具有特定键的字典中添加多个值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!