[英]how can i get all the values for the same key in different dictionary and dictionaries are stored in a list
[英]How get all people with the same height in a list of dictionaries
我有這個字典列表:
data = [{"nome": "joao", "idade": "16", "altura": "167"},
{"nome": "Gabriel", "idade": "12", "altura": "167"},
{"nome": "Rodrigo", "idade": "14", "altura": "170"},
{"nome": "Filipe", "idade": "21", "altura": "167"}]
我需要返回的是這樣的:
{167: 3, 170: 1}
看起來很簡單,它必須有一些東西可以一步完成,但我就是做不到(我不能使用任何類型的導入)。 有誰知道怎么做?
from collections import Counter
result = Counter(d["altura"] for d in data)
print(result)
# result: Counter({'167': 3, '170': 1})
heights = {}
for i in data:
if i["altura"] in heights:
heights[i["altura"]] += 1
else:
heights[i["altura"]] = 1
print(heights)
一個可能的解決方案是
obj = [itm["altura"] for itm in data]
{key: obj.count(key) for key in set(obj)}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.