如何计算值在python中嵌套字典中出现的次数?

时间:2017-09-25 06:02:16

标签: python dictionary

我有一本字典词典,例如:

d={'object1':{'time1':['value1','value2'],'time2':['value1','value4']},

' Object2的' {'时间1':['值1'' value6&#39],'时间2' :' value7'' value8']}}

如何迭代字典,以便我发现value1总共出现3次?

5 个答案:

答案 0 :(得分:1)

狡猾的方法是:

UIImageView

但你总是可以做一个嵌套循环。

答案 1 :(得分:1)

您可以迭代值和&像这样算:

n = 0

for list_data in d.values():
    if 'value1' in list_data:
        n = n + 1

print(n)

答案 2 :(得分:1)

您可以使用collections.Counteritertools.chain的组合来实现此目的:

>>> from itertools import chain
>>> from collections import Counter

>>> d={'time1':['value1','value2'],'time2':['value1','value4'],'time3':['value1','value5']}

>>> counter_dict = Counter(chain(*d.values()))
#    ^ dict holding the count of each value

为了获取' value1'的计数在counter_dict中,您只需访问此密钥的值:

>>> counter_dict['value1']
3

答案 3 :(得分:1)

这可能不是最优雅的解决方案,但它适用于您的嵌套字典问题:

lst = d.values()
sub_val = [temp.values() for temp in lst]
d_val = [item for sublist in sub_val for item in sublist]
d_val = [item for sublist in d_val for item in sublist]
count = d_val.count('value1')

lst是嵌套词典的列表。 sub_val为每个嵌套字典创建一个嵌套的值列表。这会产生一个双嵌套列表的列表,因此d_val展平会出现两次。最后,count返回展平列表value1d_val的出现次数。

答案 4 :(得分:1)

尝试list.count(x)

d={'object1':{'time1':['value1','value1','value2'],'time2':['value1','value4']},'object2':{'time1':['value1','value6'],'time2':['value7','value8']}}
cnt =[item for l in [v2 for v1 in d.values() for v2 in v1.values()] for item in l].count('value1')
print(cnt) # print 4