Skip to content
Advertisement

Get the number of specific dictionary values being stored in a 2-dimensional list in Python

I have a dictionary that contains fruits as keys and a 2-dimensional list including the line number and the timestamp, in which the fruit name occurs in the transcript file, as values. The 2-dimensional list is needed because the fruits appear several times in the file and I need to consider each single occurrence. The dictionary looks like this:

mydict = {
    'apple': [['1', '00:00:03,950'],  # 1
         ['1', '00:00:03,950'],  # 2
         ['9', '00:00:24,030'],  # 3
         ['11', '00:00:29,640']],  # 4
    'banana': [['20', '00:00:54,449']],  # 5
    'cherry': [['14', '00:00:38,629']],  # 6
    'orange': [['2', '00:00:06,840'],  # 7
          ['2', '00:00:06,840'],  # 8
          ['3', '00:00:09,180'],  # 9
          ['4', '00:00:10,830']],  # 10
}

Now, I would like to print the number of all fruits in total, so my desired solution is 10. Hence I want to count the number of the values, but not of each single list item, though… only of the whole list, so to say (see the comments which should clarify what I mean).

For this purpose, I tried:

print(len(mydict.values()))

But this code line just gives me the number 4 as result.

And the following code does not work for me either:

count = 0
for x in mydict: 
    if isinstance(mydict[x], list): 
        count += len(mydict[x]) 
print(count) 

Has anyone an idea how to get the number 10?

Advertisement

Answer

You can obtain the lengths of the sub-lists by mapping the them to the len function and then add them up by passing the resulting sequence of lengths to the sum function:

sum(map(len, mydict.values()))
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement