计算字典python中键的相同值的出现

时间:2019-04-11 06:43:41

标签: python python-3.x list dictionary

我在列表中有多个字典。我想从字典列表中计算某个值的出现次数。

这是字典的列表:

a = [{"a":"data1","b":"Nill","c":"data3","d":"Nill"},{"a":"dat1","b":"dat2","c":"dat3","d":"Nill"},{"a":"sa1","b":"sa2","c":"sa3","d":"Nill"}]

在这里,我想计算密钥中Nill的出现。如何使其成为可能。

这是我尝试的代码:

from collections import Counter
a = [{"a":"data1","b":"Nill","c":"data3","d":"Nill"},{"a":"dat1","b":"dat2","c":"dat3","d":"Nill"},{"a":"sa1","b":"sa2","c":"sa3","d":"Nill"}]
s = 0
for i in a:
    d = (a[s])
    #print(d)
    q = 0
    for z in d:
        print(z)
        z1=d[z]
        #print(z)
        if z1 == "Nill":
            q = q+1
            co = {z:q}
    print(co)

预期输出:

字典列表中Nill个值的计数

{a:0,b:1,c:0,d:3}

5 个答案:

答案 0 :(得分:2)

尝试一下:-


a = [{"a":"data1","b":"Nill","c":"data3","d":"Nill"},{"a":"dat1","b":"dat2","c":"dat3","d":"Nill"},{"a":"sa1","b":"sa2","c":"sa3","d":"Nill"}]

result_dict = {'a' : 0, 'b' : 0,'c' :0, 'd' : 0}
for i in a:
    for key, value in i.items():
        if value =="Nill":
            result_dict[key] +=1

print(result_dict)

答案 1 :(得分:2)

您可以通过对布尔表达式进行类似计数的方式来直接使用计数器,这利用了计数器将c2计数为1的事实。

True

答案 2 :(得分:1)

编辑:

要匹配所需的输出:

import pandas as pd
df = pd.DataFrame(a)
occ = {k: list(v.values()).count('Nill') for k,v in df.to_dict().items()}

答案 3 :(得分:1)

喜欢吗?

a = [{"a":"data1","b":"Nill","c":"data3","d":"Nill"},{"a":"dat1","b":"dat2","c":"dat3","d":"Nill"},{"a":"sa1","b":"sa2","c":"sa3","d":"Nill"}]

result = {}
for sub_list in a: # loop through the list
    for key, val in sub_list.items(): # loop through the dictionary
        result[key] = result.get(key, 0) # if key not in dictionary, add it
        if val == 'Nill': # if finding 'Nill', increment that value
            result[key] += 1

for key, val in result.items(): # show result
    print(key, val)

答案 4 :(得分:1)

尝试一下:

from collections import defaultdict

c = defaultdict(int, {i:0 for i in a[0].keys()})
for i in a: 
    for k,v in i.items():
        if v=='Nill': 
            c[k] += 1 

dict(c)将是您想要的输出。

{'a': 0, 'b': 1, 'c': 0, 'd': 3}