python - 如何在字典列表中将 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()
解决方案
而不是像这样的字典列表 -[{'query': 'one'}, {'query': 'two.'}, {'query': 'three'}...]
你可以像这样创建一个字典 - {'one': 0, 'two': 0, 'three': 0...}
where'one'
等'two'
, arequeries
和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()
这将按降序打印my_list
排序count
。
示例输出如下所示:
['two', 'three', 'one']
推荐阅读
- travis-ci - 在 travis-ci 中为安全列表之外(或阻止列表内)的分支手动触发构建
- keycloak - Keycloak:使用管理员 REST api 更改密码时如何识别用户?
- flask - sqlalchemy.exc.AmbiguousForeignKeysError:如何在 Flask SQLAlchemy 中定义两个引用相同主键的外键?
- javascript - 在打字稿中将字符串转换为对象键查找
- vue.js - 过滤接受小写或大写字符串的帖子列表
- c# - 将空布局更改为默认布局上传图片刷新页面
- jquery - 从固定宽度滚动到全屏图像
- mysql - Aurora RDS 正在重置主键
- c++ - 我不知道这条线是做什么的
- angular - 将自定义 FormControl 添加到 FormArray 时未触发验证