How to find length of dictionary values

Question:

I am pretty new to all of this so this might be a noobie question.. but I am looking to find length of dictionary values… but I do not know how this can be done.

So for example,

d = {'key':['hello', 'brave', 'morning', 'sunset', 'metaphysics']}

I was wondering is there a way I can find the len or number of items of the dictionary value.

Thanks

Asked By: Andre

||

Answers:

To find all of the lengths of the values in a dictionary you can do this:

lengths = [len(v) for v in d.values()]
Answered By: squiguy

Sure. In this case, you’d just do:

length_key = len(d['key'])  # length of the list stored at `'key'` ...

It’s hard to say why you actually want this, but, perhaps it would be useful to create another dict that maps the keys to the length of values:

length_dict = {key: len(value) for key, value in d.items()}
length_key = length_dict['key']  # length of the list stored at `'key'` ...
Answered By: mgilson

Lets do some experimentation, to see how we could get/interpret the length of different dict/array values in a dict.

create our test dict, see list and dict comprehensions:

>>> my_dict = {x:[i for i in range(x)] for x in range(4)}
>>> my_dict
{0: [], 1: [0], 2: [0, 1], 3: [0, 1, 2]}

Get the length of the value of a specific key:

>>> my_dict[3]
[0, 1, 2]
>>> len(my_dict[3])
3

Get a dict of the lengths of the values of each key:

>>> key_to_value_lengths = {k:len(v) for k, v in my_dict.items()}
{0: 0, 1: 1, 2: 2, 3: 3}
>>> key_to_value_lengths[2]
2

Get the sum of the lengths of all values in the dict:

>>> [len(x) for x in my_dict.values()]
[0, 1, 2, 3]
>>> sum([len(x) for x in my_dict.values()])
6
Answered By: Lundy
d={1:'a',2:'b'}
sum=0
for i in range(0,len(d),1):
   sum=sum+1
i=i+1
print i

OUTPUT=2

Answered By: SHAIK GOUSIA

Let dictionary be :
dict={'key':['value1','value2']}

If you know the key :
print(len(dict[key]))

else :
val=[len(i) for i in dict.values()]
print(val[0])
# for printing length of 1st key value or length of values in keys if all keys have same amount of values.

Answered By: Siddhi Jha

A common use case I have is a dictionary of numpy arrays or lists where I know they’re all the same length, and I just need to know one of them (e.g. I’m plotting timeseries data and each timeseries has the same number of timesteps). I often use this:

length = len(next(iter(d.values())))
Answered By: adamconkey
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.