简体   繁体   中英

counting strings in list using dictionary in python 3

i have a list of list with only strings and i have to create a dictionary with strinds as keys and their count in list of list as value. should look like this:

[[‘dolphin’, ‘bomb’, ‘spider’], [‘eye’, ‘bomb’, ‘fire’],
[‘spider’, ‘fire’, ‘lock’], [‘bomb’, ‘lock’, ‘tree’]]

and the output should be with every key in different line:

dolphin 1
bomb 3
spider 2
eye 1
fire 2
lock 2
tree 1

this is my code:

dic_count={}
count=1
def print_symbols_counts(deck):
    for i in range(len(deck)-1):
        for j in deck[i]:
            if j in deck[i+1]:
                dic_count[j]=count+1
            else:
                dic_count[j]=count
    return dic_count
  

but sudly i cant get the correct output (this is my output):

{'dolphin': 1, 'bomb': 1, 'spider': 1, 'eye': 1, 'fire': 1, 'lock': 2}

thank you:)

You could just flatten the list and then use Collections.Counter :

from collections import Counter
flat_list = [item for sublist in lst for item in sublist]
result = Counter(flat_list)

See How to make a flat list out of list of lists? and How can I count the occurrences of a list item? .

EDIT: Since OP is not allowed to use Counter :

flat_list = [item for sublist in lst for item in sublist]
result = dict((x, flat_list.count(x)) for x in set(flat_list))
llist2 = [["bomb", "bomb", "spider"], ["eye", "bomb", "fire","spider"], ["bomb", "lock", "tree","fire"]]

dictionary = {}
for i in llist2:
    for k in i:
        if k not in dictionary:
            dictionary[k]=1
        else:
            dictionary[k]+=1
#output

{'bomb': 4, 'spider': 2, 'eye': 1, 'fire': 2, 'lock': 1, 'tree': 1}

This should do the job.

The code iterates over every list in llist2 then for each list, it checks if its elements are already a key in the dictionary . If not, it creates the key and assigns to it 1. If already in, it increments the count.

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