Home > Blockchain >  sorting elements in the list's(as values) in the dictionary
sorting elements in the list's(as values) in the dictionary

Time:09-29

In the below-mentioned dictionary, how do sort elements of the lists (list's as values of dict) in descending order?

my_Dict = {'item1': [7, 1, 9], 'item2': [8, 2, 3], 'item3': [9, 3, 11] }

thank you in advance! _

CodePudding user response:

The simplest way would be:

my_Dict = {'item1': [7, 1, 9], 'item2': [8, 2, 3], 'item3': [9, 3, 11] }

for key,value in my_Dict.items():
  my_Dict[key] = sorted(value, reverse = True)

print(my_Dict)

Outputs:

{'item1': [9, 7, 1], 'item2': [8, 3, 2], 'item3': [11, 9, 3]}

This sorts the dictionary 'in place' - without creating a new dictionary in memory!

Edit: Thanks for the comment - changed list.sort() to sorted()

CodePudding user response:

Try this.

1.

my_Dict = {'item1': [7, 1, 9], 'item2': [8, 2, 3], 'item3': [9, 3, 11] }

sortedDcit = {k:sorted(v, reverse=True) for k,v in my_Dict.items()}

print(sortedDcit)

Or use this.

2.

my_Dict = {'item1': [7, 1, 9], 'item2': [8, 2, 3], 'item3': [9, 3, 11] }

for k in my_Dict:
  my_Dict[k].sort(reverse = True)

print(my_Dict)

OR

3.

my_Dict = {'item1': [7, 1, 9], 'item2': [8, 2, 3], 'item3': [9, 3, 11] }

for k,v in my_Dict.items():
  my_Dict[k] = sorted(v,reverse = True)

print(my_Dict)


Output

{'item1': [9, 7, 1], 'item2': [8, 3, 2], 'item3': [11, 9, 3]}
  • Related