[英]Getting number of key:value pairs for a dict key
I have a dictionary with a nested dictionary as value for each key, and I want to check the size of this dictionary value. 我有一本字典,其中一个嵌套字典作为每个键的值,并且我想检查此字典值的大小。
dict = {
'1':{'2':3,'4':4},
'2':{'3':5,'4':3}
}
For this example, I should get length_of(dict['1']) = 2 对于此示例,我应该得到length_of(dict ['1'])= 2
How to get that? 如何获得?
只需使用内置的len
len(d['1'])
只需在最后添加
print len(dict['1'])
If you want the total number of k:v pairs within each entry of the dictionary, you can use sum(len(dict[k]) for k in dict)
. 如果要在字典的每个条目中使用k:v对的总数,则可以对
sum(len(dict[k]) for k in dict)
使用sum(len(dict[k]) for k in dict)
。
However, don't use the name dict
, since it's the built-in class name for dictionaries. 但是,请勿使用名称
dict
,因为它是dict
的内置类名称。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.