1

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

Dude
  • 145
  • 1
  • 9

3 Answers3

1

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?

Beny Gj
  • 607
  • 4
  • 16
1

IIUC, Use:

# sorted in ascending order.
services = sorted(ServiceDict, key=lambda k: ServiceDict[k][0])
print(services)

This prints:

['Service02', 'Service01', 'Service04', 'Service03']
Shubham Sharma
  • 68,127
  • 6
  • 24
  • 53
1

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']
Dhaval Taunk
  • 1,662
  • 1
  • 9
  • 17