0

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

Ziv Aqua
  • 47
  • 6
  • Where you write `dic_count[j]=count+1`, in plain English, what is the intent of the line? Now, where does the value of `count` on the right-hand side come from? Similarly for `dic_count[j]=count`. When that line executes, how many times has the word `j` been seen? Therefore, what value should be stored as `dic_count`? – Karl Knechtel Nov 29 '20 at 21:26
  • With the condition `if j in deck[i+1]:`, what purpose is *that* for? It seems like you need to handle `dic_count[j]` differently depending on... what condition, in plain English? And why? – Karl Knechtel Nov 29 '20 at 21:28

2 Answers2

1

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))
Ayush Garg
  • 2,234
  • 2
  • 12
  • 28
0
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.

ombk
  • 2,036
  • 1
  • 4
  • 16