Reputation: 85
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
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
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
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
Reputation: 62835
Quite easy:
test = {'foo' : ['foo1', 'foo2'], 'foo3' : ['foo4', 'foo5', 'foo6']}
len(test['foo'])
# 2
Upvotes: 0