Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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']}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...