Maxperezt
Maxperezt

Reputation: 67

Is there a simpler way to extract the last value of a dictionary?

So I was tasked to make a function using python, that returns how many values there is in a dictionary that ONLY contains lists. An example of such a dictionary would be:

animals = { 'a': ['alpaca','ardvark'], 'b': ['baboon'], 'c': ['coati']}

The values inside the list also count towards the total values returned from the function, which means that it has to return 4. This is the function I made:

def how_many(aDict):
'''
aDict: A dictionary, where all the values are lists.

returns: int, how many values are in the dictionary.
'''
numValues = 0;
while aDict != {}:
    tupKeyValue = aDict.popitem();
    List = tupKeyValue[1];
    numValues += len(List);

return numValues;

So I was wondering if there was a way to pop the last value of a dictionary without popitem() which extracts the key-value pair. Just trying to make it as simple as possible.

Upvotes: 2

Views: 55

Answers (1)

Sash Sinha
Sash Sinha

Reputation: 22360

Since you are not using the dictionaries keys maybe you could just use values() along with sum():

def how_many(d):
    return sum(len(v) for v in d.values())

animals = {'a': ['alpaca', 'ardvark'], 'b': ['baboon'], 'c': ['coati']}
print(how_many(animals))

Output:

4

Upvotes: 2

Related Questions