Home > Software design >  How dictionaries are getting implemented here?
How dictionaries are getting implemented here?

Time:06-12

I am new to python. I came across this code while studying dictionaries. One thing which I don't get is how counts, which is only declared as a dictionary in the first line , is used in the if statement for searching names within it when no value has been added to it.

counts = dict() 
names = ['csev' , 'cwen' , 'csev' , 'zqian' , 'cwen' ]
for name in names:
    if name not in counts: 
        counts[name] = 1
    else: 
        counts[name] = counts[name] 1
print(counts)     # typo

CodePudding user response:

If you can try in this platform - https://pythontutor.com/ You could see what's happening in each step of execution. But here is a simple explanation.

counts = dict()     # 
names = ['csev' , 'cwen' , 'csev' , 'zqian' , 'cwen' ]

for name in names:            # looping each name in the list
    if name not in counts:    # check if it in the dict. counts (by key)
        counts[name] = 1      # if not, add it, and value set to 1 initially
    else: 
        counts[name] = counts[name] 1   # if existing, add value 1
print(count)

output

 {'csev': 2, 'cwen': 2, 'zqian': 1}
  • Related