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}]
感謝您的建議。
非常感謝@tobias_k,你的解決方案完美運作 – Tiger1