简体   繁体   中英

How to increment key values of dict by 1 inside a list of dictionaries?

I have a list of dictionaries. I want to get top 5 query based on how many times the particular query is entered by the user. How can I do this ?

The below is my approach for this problem but this way I am not being able to solve the problem.

def get_top_5_query():
    my_list = [{'query': 'one'}, {'query': 'two.'}, {'query': 'three'}...]
    q = input("Enter query:") # this will be one, two etc(key query value)
    q_count = 0
    new_list = []
    if q in list:
      q_count += 1
    # now increment matched query count by 1:
    # for example
      #if q is 'one' then list should be
       # [{'query': 'one', count:1}]
       

def main():
    choice = "y"
    while choice == "y":
        get_top_5_query()
        choice = input("Enter 'y' if Yes and 'n' if No(y/n) : ").lower()
        if choice == "n":
            print("Bye!!")


if __name__ == '__main__':
    main()



    

Instead of a list of dictionaries like this - [{'query': 'one'}, {'query': 'two.'}, {'query': 'three'}...] You could just create a dictionary like this - {'one': 0, 'two': 0, 'three': 0...} where 'one' , 'two' etc., are queries and 0 's are counts .

def get_top_5_query(my_list):
    q = input("Enter query:") # this will be one, two etc(key query value)
    if q in my_list:
      my_list[q] += 1
    
       
def main():
    choice = "y"
    my_list = {'one': 0, 'two': 0, 'three': 0}
    while True:
        choice = input("Enter 'y' if Yes and 'n' if No(y/n) : ").lower()
        if choice == "n":
            print("Bye!!")
            break
        else:
            get_top_5_query(my_list)
    print(list(dict(sorted(my_list.items(), key=lambda x: -x[1])).keys()))


if __name__ == '__main__':
    main()

This prints the my_list sorted by the count in descending order.

Sample output looks like this:

['two', 'three', 'one']

Do something like follow:-


my_list = [{'query': 'one'}, {'query': 'two'}, {'query': 'three'}]
def get_top_5_query():
    global my_list
    q = input("Enter query:") # this will be one, two etc(key query value)
    for i in my_list:
        if q in i.values():
            if 'count' in i:
                i['count']+=1
            else:
                i['count']=1

       

def main():
    choice = "y"
    while choice == "y":
        get_top_5_query()
        choice = input("Enter 'y' if Yes and 'n' if No(y/n) : ").lower()
        if choice == "n":
            print("Bye!!")


if __name__ == '__main__':
    main()

Does this work for you?

def get_top_5_query(new_dict):
    my_list = [{'query': 'one'}, {'query': 'two.'}, {'query': 'three'}]
    query = input("Enter query:") 
    if query in new_dict.keys():
        new_dict[query] += 1
    else:
        new_dict[query] = 1
    return new_dict       

def main():
    result_dict = {}
    choice = "y"
    while choice == "y":
        result_dict = get_top_5_query(result_dict)
        choice = input("Enter 'y' if Yes and 'n' if No(y/n) : ").lower()
        if choice == "n":
            print("Bye!!")
    
    print(sorted(result_dict.items(), key=lambda q: q[1], reverse=True))

if __name__ == '__main__':
    main()

This is what the response looks like

[('two', 2), ('one', 1), ('three', 1)]

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