簡單的例子這裏字典的增量值:的Python:存儲在一個列表
我想有這充滿字典對於每一個類型的動物名單。
打印應該是這樣的:
dictlist_animals = [{'type':'horse','amount':2},
{'type':'monkey','amount':2},
{'type':'cat','amount':1},
{'type':'dog','amount':1}]
因爲有些動物存在我不止一次添加了一個名爲「量」,這應該算作是如何存在的每一種類型的許多動物關鍵更多。
我不確定'if-case'是否正確,我在'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