0

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
  • 125
  • 1
  • 9

3 Answers3

0

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
  • 597
  • 3
  • 16
0

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
  • 52,812
  • 6
  • 20
  • 45
0

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,634
  • 1
  • 8
  • 17