Brick Top
Brick Top

Reputation: 85

Know how many entries a key has in a dictionary

I couldn't find this solution anywhere, must be simple.

Say you have a dictionary with lists

test = {'foo' : ['foo1', 'foo2'], 'foo3' : ['foo4', 'foo5', 'foo6']}

How can I count how many entries the foo key on test has?

IE the answer for 'foo' would be '2' or for 'foo3' would be '3'.

Upvotes: 0

Views: 228

Answers (5)

Anurag
Anurag

Reputation: 3114

If you want to get the count dynamically, in case you don't know the key names then try this -

test = {'foo' : ['foo1', 'foo2'], 'foo3' : ['foo4', 'foo5', 'foo6']}
for key in test:
    print len(test[key])
#2
#3

The use case could be like find the 'key' which has maximum number of elements.

Upvotes: 0

aIKid
aIKid

Reputation: 28302

Here is a good way, making a dictionary of length, and providing an 'answer':

>>> test = {'foo' : ['foo1', 'foo2'], 'foo3' : ['foo4', 'foo5', 'foo6']}
>>> lengths = {k:len(v) for k, v in test.items()}
>>> lengths['foo']
2

Also keep in mind that a dictionary can only store a single value for each key. What you're having is not multiple entries, but one list with multiple items :)

Hope this helps!

Upvotes: 0

mmmmmm
mmmmmm

Reputation: 32710

Because it is a dictionary the foo key has one and only on entry in the dictionary.

However the value corresponding to the foo key is a list. That list has a length

e.g.

print( len(test['foo']))

Upvotes: 2

om-nom-nom
om-nom-nom

Reputation: 62835

Quite easy:

test = {'foo' : ['foo1', 'foo2'], 'foo3' : ['foo4', 'foo5', 'foo6']}
len(test['foo'])      
# 2

Upvotes: 0

furins
furins

Reputation: 5048

as easy as

print len(test['foo'])

Upvotes: 1

Related Questions