+ 1
How to sort dictionary? In python.
Help me
3 odpowiedzi
+ 8
Here are some examples.
https://stackoverflow.com/questions/613183/how-do-i-sort-a-dictionary-by-value
https://www.geeksforgeeks.org/JUMP_LINK__&&__python__&&__JUMP_LINK-sort-python-dictionaries-by-key-or-value/
- - - - - - - - - - - - - - - - -
Just a quick example:
x = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}
x = {k: v for k, v in sorted(x.items(), key=lambda item: item[0])}
print(x)
>> {0: 0, 1: 2, 2: 1, 3: 4, 4: 3}
# sorted by key
- - - - - - - - - - - - - - - - - --
x = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}
x = {k: v for k, v in sorted(x.items(), key=lambda item: item[1])}
print(x)
>> {0: 0, 2: 1, 1: 2, 4: 3, 3: 4}
#sorted by value
+ 3
Thanks 《 Nicko12 》 bro and Dino Wun (Use the search bar plz!) bro