forloop count for a nestedlist

57 Views Asked by At

Hey all I'm struggling figure out to count in python i need to it count names then it has to adds them to a dictionary or if there's is another alternative way , so from the list it needs to match the name in the second list

list_1 = ['red', 'blue', 'green']
nested_list_1= [['red','hair','peaches'],['green', 'hair', 'roses'],['green', 'same', 'roses'],['red', 'same', 'roses'],['green', 'same', 'roses']]
dic = {}
count = 0
for x in list_1:

    # print(x)
    # count = 
    for y in nested_list_1:
   
        if x in y[0]:
           
            count +=1
            dic[y[0]] = count

I have tried adding counter loop it count the name but only for the first it then counts the second name in the list but it doesn't count correctly after that

I need to iterate and count the name and alos need to count if that list has hair or not. Basically i need to count that and add it to the dic and make it like nested dic so for example, with the pseudo code red [ appeared; 2 hair ; 1] green [ appeared; 3 hair ; 0

1

There are 1 best solutions below

5
trincot On

You cannot do this with just one counter. I suppose that for each distinct word you'll want a separate count, so use the entry in dic to see what the previous count was, and add one to it.

Secondly, for the key in your dictionary you don't want to use y[0], but x, as that is the word you're counting:

for x in list_1:
    for y in nested_list_1:
        if x in y[0]:
            if x not in dic:
                dic[x] = 1
            else:
                dic[x] +=1

If you want also an entry in the result for the strings that were not found (so with a count of 0), then first create your dictionary, and iterate the nested list only once:

dic = { key: 0  for key in list_1 }
for y in nested_list_1:
    for x in y:
        if x in dic:
            dic[x] +=1