0

Hi ,

I'm a newbie to python.
I would appreciate if someone can help me in solving this one.

Say i have a string str1 = "a:1,a:2,b:3,c:4"
I want to get output in form of a dictionary like d= {a:3 , b:3 , c:4}

i.e

if in the string a repeats twice I need to add a:1 and a:2 and replace a with updated value(3 here) and get it in dictionary format.

Please suggest a way out.

Thanks for any inputs.

2
Contributors
2
Replies
5
Views
8 Years
Discussion Span
Last Post by you2
0

This is pretty straight forward:

>>> my_dict = {}
>>> for item in str1.split(','):
...     key,value = item.split(':')
...     if my_dict.get( key ):
...         my_dict[ key ] += int( value )
...     else:
...         my_dict[ key ] = int( value )
...     
>>> my_dict
{'a': 3, 'c': 4, 'b': 3}
>>>

If there's any piece that you don't understand.. ask and I'll explain

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.