0

这是我的字典列表:

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

感谢您的建议。

4

1 回答 1

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}]
于 2013-10-13T10:18:50.107 回答