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
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()]
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'}]
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.
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()]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.