Reputation: 29
If I have a dictionary like this:
dict = {'a': ['Menny','Adam'], 'b': ['Steff','Bentz', 'Arik'], 'c': ['Helen','Stephonich', 'Marry', 'Kenny', 'Mike', 'Pring']
and so on.
I want to do a function that counts how many values there's on a key. For example:
>>> func(d, a)
>>> 2
>>> func(d, c)
>>> 6
I know I need to use d.values, sum(len(values)) or something like this, but I don't know how. please help me. Thanks.
It's for a big project I'm working on and I'm stuck. Thanks again.
Upvotes: 0
Views: 88
Reputation: 371
Fisrt I suggest that you should read some python tutorials, if your have a big project to write but still dont know the basic usage of python.
You should not use dict to refer a dictionary. dict
is python's keyword. Just like you would not define a variable whose name is int
in C.
If you just want to get the length of an iterable object just use len(). it returns an int object. And function sum() returns the sum of an iterable object. So you cannot use sum(len(your_dict))
, it's like sum
(4)` and would not return anything.
Your dict.value
is not a legal function or sth. Use dict.values()
, which returns a tuple that contains every value in key-value pair, similarly dict.keys()
returns all keys as a tuple.
Upvotes: 3
Reputation: 239623
mydict = {'a': [4,'Adam'], 'b': [3,'John', 4], 'c': [4,'Stephonich', 3, 8, 8, 34]}
def func(myDict, key):
return len(myDict[key])
print func(mydict, "a")
print func(mydict, "b")
print func(mydict, "c")
Output
2
3
6
Upvotes: 2