简体   繁体   中英

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?

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()))

@blhsing solution is the best. If you want to keep it with loops, you can do:

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
}

n_fruits = 0
for fruit, occurences_of_fruit in mydict.items():
    # increment n_fruits by the number of occurence of the fruit
    # BTW occurences_of_fruit and mydict[fruit] are the same thing
    n_fruits += len(occurences_of_fruit)

print(n_fruits)  # 10

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM