![](/img/trans.png)
[英]Need help in extracting value counts from a list of dictionaries using python
[英]Need help in extracting key list from List of dictionaries and corresponding counts using Python
嗨,我正在寻找使用 Python 从字典列表及其相应计数中提取所有键的列表。 使用下面的代码,但不能这样做有人可以在这方面帮助我
数据看起来像这样,
people = [{'name': "Tom", 'age': 10, "city" : "NewYork"},
{'name': "Mark", 'age': 5, "country" : "Japan"},
{'name': "Pam", 'age': 7, "city" : "London"},
{'name': "Tom", 'hight': 163, "city" : "California"},
{'name': "Lena", 'weight': 45, "country" : "Italy"},
{'name': "Ben", 'age': 17, "city" : "Colombo"},
{'name': "Lena", 'gender': "Female", "country" : "Italy"},
{'name': "Ben", 'gender': "Male", "city" : "Colombo"}]
def search(name):
p_count = 0
for p in people:
if p['name'] == name:
p_count = p_count+1
return p, p_count
search("Pam")
def search1(list_dict):
for i in list_dict:
def getList(i):
return i.keys()
search1(people)
我想输出如下,姓名:8,年龄:4,城市:3,国家:2 等等。
我是新手,有人可以帮助我吗
只需创建一个临时字典来保存计数结果,对于列表中每个字典中的每个键,使用dict.get
将计数加 1,默认值为0
,最后返回此字典。
def getKeyCount(lst):
out = {}
for d in lst:
for k in d.keys():
out[k] = out.get(k, 0) + 1
return out
getKeyCount(people)
#output
{'name': 8, 'age': 4, 'city': 5, 'country': 3, 'hight': 1, 'weight': 1, 'gender': 2}
您可以制作一个哈希表,并遍历每个
hash = {}
for d in list_dict:
for k in d.keys():
if k not in hash:
hash[k] = 0
hash[k] += 1
print(hash)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.