Convert list into dictionary in python -


i have python dictionary of form :

a1 = {         'sfp_1': ['cat', '3'],          'sfp_0': ['cat', '5', 'bat', '1']      } 

the end result need dictionary of form :

{'bat': '1', 'cat': '8'} 

i doing this:

b1 = list(itertools.chain(*a1.values())) c1 = dict(itertools.izip_longest(*[iter(b1)] * 2, fillvalue="")) 

which gives me output:

>>> c1 {'bat': '1', 'cat': '5'} 

i can iterate on dictionary , can give me more pythonic way of doing same?

using defaultdict:

import itertools collections import defaultdict  a1 = {u'sfp_1': [u'cat', u'3'], u'sfp_0': [u'cat', u'5', u'bat', u'1']}  b1 = itertools.chain.from_iterable(a1.itervalues()) c1 = defaultdict(int) animal, count in itertools.izip(*[iter(b1)] * 2):     c1[animal] += int(count) # c1 => defaultdict(<type 'int'>, {u'bat': 1, u'cat': 8})  c1 = {animal: str(count) animal, count in c1.iteritems()} # c1 => {u'bat': '1', u'cat': '8'} 

Comments

Popular posts from this blog

basic authentication with http post params android -

vb.net - Virtual Keyboard commands -

How to get multiresult with multicondition in Sql Server -