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.

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

THanks a lot..this works fine

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.