Dictionaries

Aus Micropython Referenz
Zur Navigation springen Zur Suche springen


Dictionaries sortieren[Bearbeiten | Quelltext bearbeiten]

Quelle: https://aashishkumar12376.medium.com/6-python-dictionary-tricks-to-supercharge-your-application-ed5abe24d3bb

5. Sort Dictionaries by Keys or Values[Bearbeiten | Quelltext bearbeiten]

Need a sorted dictionary? Use sorted() with items():

data = {"banana": 3, "apple": 5, "orange": 2}

sorted_by_key = dict(sorted(data.items()))  
sorted_by_value = dict(sorted(data.items(), key=lambda x: x[1]))

print(sorted_by_key)   # {'apple': 5, 'banana': 3, 'orange': 2}
print(sorted_by_value) # {'orange': 2, 'banana': 3, 'apple': 5}


Links:[Bearbeiten | Quelltext bearbeiten]