How to get all keys from Ordered Dictionary?

pobro123 picture pobro123 · Apr 17, 2016 · Viewed 24.4k times · Source
def izracunaj_dohvatljiva_stanja(funkcije_prijelaza):
    dohvatljiva = []
    dohvatljiva.extend(pocetno_stanje)
    pomocna = collections.OrderedDict
    for i in xrange(len(dohvatljiva)):
        for temp in pomocna.keys(): <-----------------------------------this line
            if temp.split(',')[0] == dohvatljiva[i]:
                if funkcije_prijelaza.get(temp) not in dohvatljiva:
                    dohvatljiva.extend(funkcije_prijelaza.get(temp))

I am trying to get all keys from ordered dict so i can iterate over it but after running error occurs: click for pic

Answer

arsho picture arsho · Apr 3, 2017

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']