How to get all keys from Ordered Dictionary?
It's quite an old thread to add new answer. But when I faced a similar problem and searched for it's solution, I came to answer this.
Here is an easy way, we can sort a dictionary in Python 3(Prior to Python 3.6).
import collections
d={
"Apple": 5,
"Banana": 95,
"Orange": 2,
"Mango": 7
}
# sorted the dictionary by value using OrderedDict
od = collections.OrderedDict(sorted(d.items(), key=lambda x: x[1]))
print(od)
sorted_fruit_list = list(od.keys())
print(sorted_fruit_list)
Output:
OrderedDict([('Orange', 2), ('Apple', 5), ('Mango', 7), ('Banana', 95)])
['Orange', 'Apple', 'Mango', 'Banana']
Update:
From Python 3.6 and later releases, we can sort dictionary by it's values.
d={
"Apple": 5,
"Banana": 95,
"Orange": 2,
"Mango": 7
}
sorted_data = {item[0]:item[1] for item in sorted(d.items(), key=lambda x: x[1])}
print(sorted_data)
sorted_fruit_list = list(sorted_data.keys())
print(sorted_fruit_list)
Output:
{'Orange': 2, 'Apple': 5, 'Mango': 7, 'Banana': 95}
['Orange', 'Apple', 'Mango', 'Banana']
The correct way to instantiate an object in Python is like this:
pomocna = collections.OrderedDict() # notice the parentheses!
You were assigning a reference to the class.
For anyone winding up here when what they really want is this:
dict_keys = list(my_dict.keys())
How to return dictionary keys as a list in Python?