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

Python function which will count the total number of items in values from a dictionary and return another dictionary with item count

data = {'customer1': ['milk', 'bread'],
 'customer2': ['butter'],
 'customer3': ['beer', 'diapers'],
 'customer4': ['milk', 'bread', 'butter'],
 'customer5': ['bread']}

I want the Python function output to be

{'milk': 2, 'bread': 3, 'butter': 2, 'beer': 1, 'diapers': 1} 

and then also build a histogram on this data

res = dict()
for key in customer_data.keys():
  
    res[key] = len(set([sub[key] for sub in customer_data]))

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

>Solution :

You can use Counter class from collections module.

>>> data = {
...     "customer1": ["milk", "bread"],
...     "customer2": ["butter"],
...     "customer3": ["beer", "diapers"],
...     "customer4": ["milk", "bread", "butter"],
...     "customer5": ["bread"],
... }
>>> 
>>> from collections import Counter
>>>
>>> print(Counter([val for key, value in data.items() for val in value]))
Counter({'bread': 3, 'milk': 2, 'butter': 2, 'beer': 1, 'diapers': 1})

Alternativey you can also do,

>>> data = {
...     "customer1": ["milk", "bread"],
...     "customer2": ["butter"],
...     "customer3": ["beer", "diapers"],
...     "customer4": ["milk", "bread", "butter"],
...     "customer5": ["bread"],
... }
>>> 
>>> 
>>> 
>>> result = {}
>>> 
>>> for _, values in data.items():
...     for value in values:
...         result[value] = result.setdefault(value, 0) + 1
... 
>>> print(result)
{'milk': 2, 'bread': 3, 'butter': 2, 'beer': 1, 'diapers': 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