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 to create and print a Dictionary that has keys as the names in list and their values as number of times the name appears on the list

I have a list of names:

list = ['Ginger', 'Willow', 'Scout', 'Roscoe', 'Bear', 'Kobe', 'Baxter', 'Zara', 'Fiona', 'Milo', 'Oakley', 'Dakota', 'Prince', 'Bruno', 'Panda', 'Dexter', 'Ziggy', 'Roscoe', 'Lucy', 'Boomer', 'Fiona', 'Ella', 'Emma', 'Oakley']

Using this list, I’ve created the following dictionary:

listA = {"G": "Ginger", "W": "Willow", "S": "Scout", "R": ["Roscoe", "Roscoe"], "B": ["Bear", "Baxter", "Bruno", "Boomer"], "K": "Kobe", "Z": ["Zara", "Ziggy"], "F": ["Fiona", "Fiona"], "M": "Milo", "O": ["Oakley", "Oakley"], "D": ["Dakota", "Dexter"], "P": ["Prince", "Panda"], "L": "Lucy", "E": ["Ella", "Emma"]}

Printing the keys from the dictionary:

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

for key in listA.keys():
    print(key)

I get:

G
W
S
R
B
K
Z
F
M
O
D
P
L
E

How can I get the number of times that each name appears in the list?

>Solution :

You don’t need listA; collections.Counter does exactly what you’re looking for.

import collections
data = ['Ginger', 'Willow', 'Scout', 'Roscoe', 'Bear', 'Kobe', 'Baxter', 'Zara', 'Fiona', 'Milo', 'Oakley', 'Dakota', 'Prince', 'Bruno', 'Panda', 'Dexter', 'Ziggy', 'Roscoe', 'Lucy', 'Boomer', 'Fiona', 'Ella', 'Emma', 'Oakley']
counter = collections.Counter(data)

print(counter) # Prints counter object.
counter_as_dict = dict(counter) # Can be transformed into a dictionary using dict().
print(counter_as_dict.keys()) # Prints names in dictionary.
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