Reputation: 39
I have a dictionary where I have a key with more than one value, I want to create a new dictionary with the same key but the value is the length of the previous
I have:
dict = {'key1': ['value1'], ['value2'], ['value3'], {'key2': ['value4'], ['value5']}
I want:
dict_bis = {'key1': '3', 'key2': '2'}
Upvotes: 0
Views: 27
Reputation: 21893
Just use a for loop and dict.items()
to loop over the existing dict, and len()
to find the length of the values:
dict_bis = {}
for key, values in dict.items():
dict_bis[key] = len(values)
Or the same using a dict comprehension:
dict_bis = {key: len(values) for key, values in dict.items()}
Upvotes: 1