2013-10-13 65 views
0

下面的列表詞典的數量是我的字典清單:的Python:計數,其中一個關鍵出現在字典

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

試試這個(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}] 
+0

非常感謝@tobias_k,你的解決方案完美運作 – Tiger1

相關問題