计算每个字典键中包含一个值的值的数量

我有一个带有 200e3 个整数键的字典,每个键有一个或两个值(字符串)。

我需要编写逻辑来检查每个键是否具有多个值,如果是,则添加到列表中。

my_dict = defaultdict(list)
my_dict = {1: ['789456', '456123'], 2: '123456', 3: '987654'}
final = []

这是我最初的解决方案。这适用于两个值,但当只存在一个值时返回字符的长度。

for key, value in my_dict.items():
    if len(value) > 1:
        final.append(key)
    else:
        continue

我试过 enumerate 但它只返回范围。

for x in enumerate(my_dict.items()):
    print(x)

我想出了这个解决方案,但我不确定使用时是否会有任何问题defaultdict(list)。或者,如果有更大的问题,我可能看不到。

for key, value in my_dict.items():
    if isinstance(value, list):
       final.append(key)
    else:
       continue

回答

请试试这个:

final = [k for k,v in my_dict.items() if type(v) == list and len(v) > 1]

或在您的代码中:

for key, value in my_dict.items():
    # only this additional condition is present before `and`
    if type(value) == list and len(value) > 1:
        final.append(key)

在这里,'34534'['534', '456465']都是可迭代的,len()函数对它们都适用,因此,我们需要检查值的类型,并且只检查list.

  • I suspect that if type is list, it always means more than 1 items, so your code could become even faster, by removing the second condition (len>1)

以上是计算每个字典键中包含一个值的值的数量的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>