Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
335 views
in Technique[技术] by (71.8m points)

python - How to add multiple values in dictionary having specific key

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

error: AttributeError: 'str' object has no attribute 'append'

So is their any way to resolve this, I'm new to python please help.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Use a list instead of a string:

FinalData = {'12345,70': ['xyz'], '12345,71': ['pqr']}

and this works:

FinalData[key].append(value)

Example

key = '12345,70'
value = 'abc'
FinalData[key].append(value)
print(FinalData)

Output:

{'12345,70': ['xyz', 'abc'], '12345,71': ['pqr']}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...