简体   繁体   中英

Need help in extracting key list from List of dictionaries and corresponding counts using Python

Hi I am looking to extract list of all keys from a List of dictionaries and their corresponding counts using Python. Used below code but counden't do it can some one help me in this regard

The Data looks like this,

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)

I want out put like the following, name: 8, age: 4, City:3, Country: 2 etc..

I am new to this can some one help me in this

Just create a temporary dictionary to hold the count result, and for each key in each dictionary of the list, increase the the count by 1 using dict.get with default value as 0 , finally return this dictionary.

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}

You can make a hash table, and iterate over the keys of each

hash = {}
for d in list_dict:
    for k in d.keys():
        if k not in hash:
            hash[k] = 0
        hash[k] += 1

print(hash)

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM