Nzh
Nzh

Reputation: 61

How to get number of all elements in values of dictionary, where is value is a list, give the int number python

I have a dictionary where the values are lists, and I would like to know how many elements in lists associated with each key. I've found here this one. But I need total number of elements only for one key. for example for

>>> from collections import Counter
>>> my_dict = {'I': [23,24,23,23,24], 'P': [17,23,23,17,24,12]}
>>> {k: Counter(v) for k, v in my_dict.items()}
{'P': Counter({17: 2, 23: 2, 24: 1, 12: 1}), 'I': Counter({23: 3, 24: 2})}

For example {P:6}, will be better if it give just number, count_elements=5

Upvotes: 0

Views: 124

Answers (3)

jamylak
jamylak

Reputation: 133674

>>> my_dict= {'I':[23,24,23,23,24],'P':[17,23,23,17,24,12]}
>>> {k: len(v) for k, v in my_dict.items()}
{'I': 5, 'P': 6}

A single key is simple:

>>> len(my_dict['P'])
6

As @Joe suggested len(my_dict.get(key, [])) works when a key doesn't exist, which potentially works, but then you can't distinguish between keys with empty lists, and keys that don't exist. You can catch the KeyError here in that case.

Upvotes: 2

mbatchkarov
mbatchkarov

Reputation: 16099

Is that what you had in mind?

my_dict= {'I':[23,24,23,23,24],'P':[17,23,23,17,24,12]}
print {k:len(v) for k, v in my_dict.items()}
{'I': 5, 'P': 6}

Upvotes: 1

Joe
Joe

Reputation: 47699

This will get the number of values for the given key key. I believe that's what the question asked.

my_dict= {"I":[23,24,23,23,24],"P":[17,23,23,17,24,12]}
number = len(my_dict.get(key, []))

Upvotes: 2

Related Questions