gpt-4o-2024-05-13· OpenAI
WildChat-4.8M (AI2)
i have a dict {a:{time:128998294},b:{time:22490024},c:{time:143099503}} sort by time in…
- User
i have a dict {a:{time:128998294},b:{time:22490024},c:{time:143099503}}
sort by time in python
- Assistant
To sort a dictionary by the values of the nested dictionaries' keys, you can use Python's sorted function along with a custom sorting key. In your case, we want to sort by the 'time' key within the nested dictionaries. Here's how you can do it:
# Original dictionary data = {'a': {'time': 128998294}, 'b': {'time': 22490024}, 'c': {'time': 143099503}} # Sorting the dictionary by the 'time' key in the nested dictionaries sorted_data = dict(sorted(data.items(), key=lambda item: item[1]['time'])) # Printing the sorted dictionary print(sorted_data)After running this code,
sorted_datawill be:{'b': {'time': 22490024}, 'a': {'time': 128998294}, 'c': {'time': 143099503}}This sorts the dictionary in ascending order based on the 'time' values. If you want it in descending order, you can add the
reverse=Trueargument to thesortedfunction:# Sorting the dictionary by the 'time' key in descending order sorted_data_desc = dict(sorted(data.items(), key=lambda item: item[1]['time'], reverse=True)) # Printing the sorted dictionary print(sorted_data_desc)