Reputation: 145
In Python 3... Say I have a dictionary with tuples as values. How would I sort the dictionary by a certain index of each tuple? For example, in the dictionary below how could I sort by the service name (Netflix, Prime etc,) at index[0] of each tuple, and return the list of Keys in that order.
ServiceDict = {'Service01': ('Netflix', 12, 100000, 'B'), 'Service02': ('Disney', 8, 5000, 'A'), 'Service03': ('Stan', 10, 20000, 'A'), 'Service04': ('Prime', 6, 30000, 'C')}
Thanks
Upvotes: 1
Views: 203
Reputation: 1672
You can try this
ServiceDict = {k: v for k, v in sorted(ServiceDict.items(), key=lambda item: item[1][0])}
print(list(ServiceDict.keys()))
Output will be-
['Service02', 'Service01', 'Service04', 'Service03']
Upvotes: 1
Reputation: 71687
IIUC, Use:
# sorted in ascending order.
services = sorted(ServiceDict, key=lambda k: ServiceDict[k][0])
print(services)
This prints:
['Service02', 'Service01', 'Service04', 'Service03']
Upvotes: 1
Reputation: 615
here the solution
{k: v for k, v in sorted(ServerDict.items(), key=lambda item: item[1])}
duplicate you can show here more How do I sort a dictionary by value?
Upvotes: 1