Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How dictionaries are getting implemented here?

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

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading