How to join the dictionary

I have data

stat=[{'state': {'europe': ['germany', 'england']}}, {'state': {'europe': ['french', 'netherland']}}, {'state': {'asian': ['japan', 'china']}}] 

Question: how to join the list? This result:

 {'state': [{'europe': ['germany', 'england', 'french', 'netherland']}, {'asian': ['japan', 'china']}]} 

I am using Python S60 with Python 2.2

+4
source share
3 answers

Naive attempt:

 r={} for d in stat: for k,v in d.iteritems(): nd = r.setdefault(k,[]) for tdk,tdv in v.iteritems(): q = filter(lambda x: tdk in x.iterkeys(),nd) if not q: q = {tdk:[]} nd.append(q) else: q = q[0] q[tdk]+=tdv print r # prints {'state': [{'europe': ['germany', 'england', 'french', 'netherland']}, {'asian': ['japan', 'china']}]} 
+3
source

In python 2.2:

 stat2 = {} for s in stat: for c in s.values(): for k, v in c.items(): if k in stat2: stat2[k] += v else: stat2[k] = v # perhaps copying here stat2 {'asian': ['japan', 'china'], 'europe': ['germany', 'england', 'french', 'netherland']} 

If you used python> 2.4, you could just use defaultdict:

 from collections import defaultdict stat2 = defaultdict(list) for s in stat: for c in s.values(): for k, v in c.items(): stat2[k] += v stat2 defaultdict(<type 'list'>, {'europe': ['germany', 'england', 'french', 'netherland'], 'asian': ['japan', 'china']}) 

And if you really wanted to:

 {'state': [dict(stat2)]} {'state': [{'asian': ['japan', 'china'], 'europe': ['germany', 'england', 'french', 'netherland']}]} 

Consider updating your version of python, 2.2 was released in 2001 ...!

+1
source

Here is a simple answer using the constructs available in Python 2.2, nothing fantastic:

 ans = {} for d1 in stat: for k1, v1 in d1.items(): if k1 not in ans: ans[k1] = [] for k2, v2 in v1.items(): for d2 in ans[k1]: if k2 in d2.keys(): d2[k2].extend(v2) break else: ans[k1].append({k2:v2}) 

The result will be as expected:

 ans => {'state': [{'europe': ['germany', 'england', 'french', 'netherland']}, {'asian' : ['japan', 'china']}]} 
+1
source

Source: https://habr.com/ru/post/1485341/


All Articles