Python:计算键在字典列表中出现的字典数

时间:2013-10-13 10:06:51

标签: python-2.7 dictionary

这是我的词典列表:

dict_list=[{'red':3, 'orange':4}, {'blue':1, 'red':2},
   {'brown':4, 'orange':7}, {'blue':4, 'pink':10}]

我的目标是获取密钥出现的字典数,并输出一个字典列表,并将计数作为值。

My attempt:
new_list=[]
count=0
new_dict={}
for x in dict_list:
    for k,v in x.iteritems():
        if k in x.values():
            count+=1
            new_dict={k:count for k in x.iteritems()}
    new_list.append(new_dict)

My result:
[{}, {}, {}, {}]

期望的结果:

[{'red':2, 'orange':2}, {'blue':2, 'red':2},
   {'brown':1, 'orange':2}, {'blue':2, 'pink':1}]

感谢您的建议。

1 个答案:

答案 0 :(得分:1)

试试这个(Python 2.6):

counts = collections.defaultdict(int)
for d in dict_list:
    for c in d:
        counts[c] += 1
new_list = [dict((c, counts[c]) for c in d) for d in dict_list]

或者,更短(Python 2.7 +):

counts = collections.Counter()
for d in dict_list:
    counts.update(d.keys())
new_list = [{c: counts[c] for c in d} for d in dict_list]

输出:

[{'orange': 2, 'red': 2}, {'blue': 2, 'red': 2}, 
 {'orange': 2, 'brown': 1}, {'blue': 2, 'pink': 1}]