k.troy2012
k.troy2012

Reputation: 344

Python: Increment value of dictionary stored in a list

Simple example here:

I want to have a list which is filled with dictionaries for every type of animal.

The print should look like this:

dictlist_animals = [{'type':'horse','amount':2},
                    {'type':'monkey','amount':2},
                    {'type':'cat','amount':1},
                    {'type':'dog','amount':1}]

Because some animals exist more than once I've added a key named 'amount' which should count how many animals of every type exist.

I am not sure if the 'if-case' is correctly and what do I write in the 'else case'?

dictlist_animals = []

animals = ['horse', 'monkey', 'cat', 'horse', 'dog', 'monkey']


for a in animals:
    if a not in dictlist_animals['type']:
        dictlist_animals.append({'type': a, 'amount' : 1})

    else:
        #increment 'amount' of animal a

Upvotes: 0

Views: 672

Answers (4)

Dima  Kudosh
Dima Kudosh

Reputation: 7376

Better to use Counter. It's create dictionary where keys are elements of animals list and values are their count. Then you can use list comprehension for creating list with dictionaries:

from collections import Counter

animals_dict = [{'type': key, 'amount': value} for key, value in Counter(animals).items()]

Upvotes: 4

sushant
sushant

Reputation: 1111

You can also use defaultdict.

from collections import defaultdict
d = defaultdict(int)
for animal in animals:
    d[animal]+= 1

dictlist_animals = [{'type': key, 'amount': value}  for key, value in d.iteritems()]

Upvotes: 1

SimoV8
SimoV8

Reputation: 1402

You can't directly call dictlist_animals['type'] on a list because they are indexed numerically. What you can do is to store this data in an intermediate dictionary and then convert it in the data structure you want:

dictlist_animals = []

animals = ['horse', 'monkey', 'cat', 'horse', 'dog', 'monkey']

animals_count = {};
for a in animals:
    c = animals_count.get(a, 0)
    animals_count[a] = c+1

for animal, amount in animals_count.iteritems():
    dictlist_animals.append({'type': animal, 'amount': amount})

Note that c = animals_count.get(a, 0) gets the current amount for the animal a if it is present, otherwise it returns the default value 0 so that you don't have to use an if/else statement.

Upvotes: 1

Prashant Puri
Prashant Puri

Reputation: 2334

Try below code,

dictlist_animals = []

animals = ['horse', 'monkey', 'cat', 'horse', 'dog', 'monkey']
covered_animals = []
for a in animals:
    if a in covered_animals:
        for dict_animal in dictlist_animals:
            if a == dict_animal['type']:
                dict_animal['amount'] = dict_animal['amount'] + 1
    else:
        covered_animals.append(a)
        dictlist_animals.append({'type': a, 'amount' : 1})
print dictlist_animals

[{'amount': 2, 'type': 'horse'}, {'amount': 2, 'type': 'monkey'}, {'amount': 1, 'type': 'cat'}, {'amount': 1, 'type': 'dog'}]

Upvotes: 1

Related Questions