我有一本字典词典,例如:
d={'object1':{'time1':['value1','value2'],'time2':['value1','value4']},
' Object2的' {'时间1':['值1'' value6&#39],'时间2' :' value7'' value8']}}
如何迭代字典,以便我发现value1总共出现3次?
答案 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.Counter
和itertools.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
返回展平列表value1
中d_val
的出现次数。
答案 4 :(得分:1)
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