簡體   English   中英

在使用 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM