Home > Back-end >  How to create and print a Dictionary that has keys as the names in list and their values as number o
How to create and print a Dictionary that has keys as the names in list and their values as number o

Time:01-24

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:

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?

CodePudding user response:

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.
  •  Tags:  
  • Related