Home > Back-end >  updating dictionary dose not work in the loop
updating dictionary dose not work in the loop

Time:08-08

H=0
 R=0
 C=0
 His=0
 Adv=0
 A=0
dic_of_genres={"Horror":H,"Romance":R,"Comedy":C,"History":His,"Adventure":Adv,"Action":A}
n=int(input())
for i in range(0,n):
    x=input().split()
    print(x)
    for items in x:
        if items =='Horror':
            H=H 1
        elif items =='Romance':
            R =1
        elif items =="Comedy":
            C =1
        elif items =="History":
            His =1
        elif items =="Adventure":
            Adv =1
        elif items =="Action":
            A =1
print(dic_of_genres) `

I can not understand why my dictionary doesn't update in each loop. Could any body help me?

CodePudding user response:

You don't need to go over each item. Note that I also added a try except in case x have different elements than dic_of_genres

for i in range(0,n):
    x= [item.capitalize() for item in input().split()]
    for genre in set(x):
               try:
                     dic_of_genres[genre]  = x.count(genre)
               except KeyError:
                     pass

print(dic_of_genres)
  • Related