Count the number of values in each dictionary key including one value

Viewed 369

I have a dict with 200e3 integer keys that have either one or two values each (strings).

I need to write logic that checks if each key has more than one value, if so add to a list.

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

This is what my initial solution. This works for two values, but returns the length of characters when only one value exists.

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

I tried enumerate but it only returns the range.

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

I came up with this solution but I'm not sure if there would be any issues with defaultdict(list) being used. Or if there's a larger issue I might not be seeing.

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

Please try this:

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

or in your code:

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)

Here, both '34534' and ['534', '456465'] are iterables and len() function works for both of them hence, we need to check the type of the value and only check length in case of the list.

Related