Search code examples
pythondictionarycollectionsenumeration

How to update the dictionary from the user input and sort according to values using python?


I have dictionary below

{0: {'STATE': 'AL', 'POPULATION': '151449859682', 'TOP_CITY': '1', 'RANK': '1'}, 1: {'STATE': 'NY', 'POPULATION': '8955557', 'TOP_CITY': '6', 'RANK': '2'}, 2: {'STATE': 'CA', 'POPULATION': '7123215', 'TOP_CITY': '10', 'RANK': '3'}, 3: {'STATE': 'PH', 'POPULATION': '68557813', 'TOP_CITY': '11', 'RANK': '4'}, 4: {'STATE': 'IN', 'POPULATION': '7678676', 'TOP_CITY': '14', 'RANK': '5'}}

I want to sort according to RANK in descending by asking from the user input

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

RANK

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

desc

expected out is below

{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'}}


Solution

  • Use sorted with a dict() constuctor and then pass the values from your input into sort, you could setup a dictionary that can pass the arguments for True/False to handle 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'}}