如何加入字典

时间:2013-06-10 00:49:01

标签: python dictionary python-2.2

我有数据

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

问题:如何在列表之间加入? 鉴于结果:

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

我正在使用Python S60和Python 2.2

3 个答案:

答案 0 :(得分:3)

天真的尝试:

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

答案 1 :(得分:1)

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

如果您使用的是python> 2.4,你可以使用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']})

如果你真的想要:

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

考虑升级你的python版本,2.2于2001年发布......!

答案 2 :(得分:1)

这是一个简单的答案,使用Python 2.2中提供的构造,没什么特别的:

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})

结果如预期:

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