Home > Enterprise >  How can I count the keys in list of dictionaries? | python
How can I count the keys in list of dictionaries? | python

Time:11-22

For example there is a list:

list = [{'brand': 'Ford', 'Model': 'Mustang', 'year': 1964}, {'brand': 'Nissan', 'model': 'Skyline', 'year': 1969} ...]

I want to count there are how many model from each. How can I do it?

By the way sorry for the bad formatting I am new here yet.

I tried this method:

model_count = {}

for i in list:
if i['Model'] in model_count:
  model_count[i]  = 1
else:
  model_count[i] = 1

And I got this error: TypeError: unhashable type: 'dict'

CodePudding user response:

Assuming the key "Model" appears in every dictionary capitalized like this, you can use the code below

my_list = [{'brand': 'Ford', 'Model': 'Mustang', 'year': 1964}, {'brand': 'Nissan', 'Model': 'Skyline', 'year': 1969}]

models = {}
for dictionary in my_list:
    model = dictionary.get('Model', None)
    if model is not None:
        models[model] = models.get(model, 0)   1

print(models)

Output:

{'Mustang': 1, 'Skyline': 1}

CodePudding user response:

The simplest way would be with collections.Counter:

from collections import Counter
models = Counter(i['Model'] for i in mylist)
  • Related