简体   繁体   English

计算python字典的特定键中的值数

[英]counting the number of values in a specific key for a python dictionary

Can someone explain this to me, and/or direct me on the right/pythonic way of doing this? 有人可以向我解释一下,和/或指导我这样做的正确/ Python方式吗?

Python 2.7. Python 2.7。

Ultimately, I am trying to loop through dictionary countsD: 最终,我试图遍历字典countsD:

countsD = {"aa": None, "bb": None, "cc": None, "dd": None} 

and for the match in a corresponding dictionary d: 对于相应字典d中的匹配项:

d = {"aa": (5689, 34, 44, 77, 88, 321), "bb": (33, 6742, 89744), "cc": (45, 98), "dd": (1, 33)}

add the count of items as a value to the corresponding matching key, to create finally this countsD 将项目计数作为值添加到相应的匹配键中,以最终创建此countsD

{"aa": 6, "bb": 3, "cc": 2, "dd": 2}

If I do this with the above 如果我这样做以上

> d = {"aa": (5689, 34, 44, 77, 88, 321), "bb": (33, 6742, 89744), "cc": (45, 98), "dd": (1, 33)}

> for key in d:

>>     print(key)
>>     print(len(d[key]))

Returned is this, which is what I want 返回的是这个,这就是我想要的

aa
6
cc
2
dd
2
bb
3

HOWEVER, if one of the values for a key only contains 1 value (entirely possible), like (see "cc"): 但是,如果某个键的值之一仅包含1个值(完全可能),例如(请参见“ cc”):

d = {"aa": (5689, 34, 44, 77, 88, 321), "bb": (33, 6742, 89744), "cc": (45), "dd": (1, 33)}

and then run the same for loop, I get an error on the "cc" key: 然后运行相同的for循环,我在“ cc”键上收到错误消息:

aa
6
cc
Traceback (most recent call last):
  File "<interactive input>", line 3, in <module>
TypeError: object of type 'int' has no len()

HOWEVER again, if I make that "cc" key have an empty value (), then all is fine again. 但是,如果我使“ cc”键具有空值(),那么一切都很好。

d = {"aa": (5689, 34, 44, 77, 88, 321), "bb": (33, 6742, 89744), "cc": (), "dd": (1, 33)}

>>> d = {"aa": (5689, 34, 44, 77, 88, 321), "bb": (33, 6742, 89744), "cc": (), "dd": (1, 33)}
>>> for key in d:
...     print(key)
...     print(len(d[key]))
... 
aa
6
cc
0
dd
2
bb
3

And in typing the title for this post just now, I was referred to Count number of values in dictionary for each key for an answer. 在刚才输入此帖子的标题时,我被引用为字典中每个答案的键的计数值个数 Great, one line! 太好了,一行! But again, for a key with just one value, it fails. 但是同样,对于只有一个值的键,它会失败。 This good: 这个好:

>>> d = {"aa": (5689, 34, 44, 77, 88, 321), "bb": (33, 6742, 89744), "cc": (), "dd": (1, 33)}
>>> new_countsD = {k: len(v) for k,v in d.items()}
>>> new_countsD
{'aa': 6, 'bb': 3, 'cc': 0, 'dd': 2}

this not, see key "cc" 这不是,请参见键“ cc”

>>> d = {"aa": (5689, 34, 44, 77, 88, 321), "bb": (33, 6742, 89744), "cc": (111), "dd": (1, 33)}
>>> new_countsD = {k: len(v) for k,v in d.items()}
Traceback (most recent call last):
  File "<interactive input>", line 1, in <module>
  File "<interactive input>", line 1, in <dictcomp>
TypeError: object of type 'int' has no len()

So, what gives?? 那么,什么给了? I feel like I am missing something stupid... 我觉得我想念一些愚蠢的东西...

Thanks for any help! 谢谢你的帮助!

In python, a single-item tuple (called a singleton) is written as (value,) , so the (111) in your input should be written as (111,) instead; 在python中,单项元组(称为单例)写为(value,) ,因此输入中的(111)应该写为(111,) otherwise it would be considered an integer of 111 . 否则将被视为111的整数。

From tuple 's documentation : tuple的文档中

A special problem is the construction of tuples containing 0 or 1 items: the syntax has some extra quirks to accommodate these. 一个特殊的问题是包含0或1项的元组的构造:语法具有一些额外的怪癖来容纳这些项。 Empty tuples are constructed by an empty pair of parentheses; 空元组由一对空括号组成; a tuple with one item is constructed by following a value with a comma (it is not sufficient to enclose a single value in parentheses). 一个带有一个项目的元组是通过在值后面加上逗号来构造的(仅将一个值括在括号中是不够的)。 Ugly, but effective. 难看,但是有效。

 >>> empty = () >>> singleton = 'hello', # <-- note trailing comma >>> len(empty) 0 >>> len(singleton) 1 >>> singleton ('hello',) 

This is happening because when you save a value like cc with only one value, it is just saved as an int and is no longer a tuple, which means it does not have a len() function. 之所以发生这种情况,是因为当您仅使用一个值来保存cc值时,它仅被保存为一个int且不再是一个元组,这意味着它没有len()函数。 You can just add a check of the value's type , such as: 您可以仅添加值type的检查,例如:

if type(d[key]) == int:
    print(1)
else:
    print(len(d[key]))

This way, you will not try to access the length property of an int , and will not get your error. 这样,您将不会尝试访问int的length属性,也不会收到错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM