首页 > 解决方案 > 如何在字典列表中将 dict 的键值增加 1?

问题描述

我有一个字典列表。我想根据用户输入特定查询的次数获得前 5 个查询。我怎样才能做到这一点 ?

以下是我解决此问题的方法,但这样我无法解决问题。

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()



    

标签: pythonlistdictionary

解决方案


而不是像这样的字典列表 -[{'query': 'one'}, {'query': 'two.'}, {'query': 'three'}...]你可以像这样创建一个字典 - {'one': 0, 'two': 0, 'three': 0...} where'one''two', arequeries0'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()

这将按降序打印my_list排序count

示例输出如下所示:

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


推荐阅读