【问题标题】:How to update the dictionary from the user input and sort according to values using python?如何根据用户输入更新字典并使用python根据值进行排序?
【发布时间】:2018-10-15 16:32:47
【问题描述】:

我下面有字典

{0: {'STATE': 'AL', '人口':'151449859682', 'TOP_CITY': '1', '排名':'1'}, 1:{'状态':'纽约', '人口':'8955557', 'TOP_CITY': '6', '排名':'2'}, 2:{'状态':'CA', “人口”:“7123215”, 'TOP_CITY': '10', '排名':'3'}, 3:{'状态':'PH', '人口':'68557813', 'TOP_CITY': '11', '排名':'4'}, 4:{'状态':'IN', '人口':'7678676', 'TOP_CITY': '14', '排名':'5'}}

我想通过从用户输入中询问,按照 RANK 降序排序

value2sort= input('Enter the value to sort')

排名

parameter= input('asc for ascending order and desc for descending order')

描述

预期低于

{4: {'STATE': 'IN', '人口':'7678676', 'TOP_CITY': '14', '排名':'5'}, 3:{'状态':'PH', '人口':'68557813', 'TOP_CITY': '11', '排名':'4'}, 2:{'状态':'CA', “人口”:“7123215”, 'TOP_CITY': '10', '排名':'3'}, 1:{'状态':'纽约', '人口':'8955557', 'TOP_CITY': '6', '排名':'2'}, 0:{'状态':'AL', '人口':'151449859682', 'TOP_CITY': '1', '排名':'1'}}

【问题讨论】:

  • 字典未排序

标签: python dictionary collections enumeration


【解决方案1】:

使用sorteddict() 构造函数,然后将输入中的值传递给排序,您可以设置一个字典,可以传递True/False 的参数来处理asc/desc

value = input('Enter the value to sort: ')
param = input('Enter "asc" for ascending and "desc" for descending order: ')
order = {'asc': False, 'desc': True}

d = dict(sorted(d.items(), key=lambda x: int(x[1][value]), reverse=order[param]))
print(d)
Enter the value to sort: RANK
Enter "asc" for ascending and "desc" for descending order: desc
{4: {'STATE': 'IN', 'POPULATION': '7678676', 'TOP_CITY': '14', 'RANK': '5'}, 3: {'STATE': 'PH', 'POPULATION': '68557813', 'TOP_CITY': '11', 'RANK': '4'}, 2: {'STATE': 'CA', 'POPULATION': '7123215', 'TOP_CITY': '10', 'RANK': '3'}, 1: {'STATE': 'NY', 'POPULATION': '8955557', 'TOP_CITY': '6', 'RANK': '2'}, 0: {'STATE': 'AL', 'POPULATION': '151449859682', 'TOP_CITY': '1', 'RANK': '1'}}

【讨论】:

  • 没有得到其他值的正确输出。输入要排序的值:TOP_CITY 升序输入“asc”,降序输入“desc”: asc 'TOP_CITY': '6' 排在字典的最后。
  • @user1464878 必须是int(x[1][value]),已修复
  • @MakbulHussain,看看更新并确保在排序中包含int
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-09
  • 1970-01-01
  • 2014-10-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多