pobro123
pobro123

Reputation: 183

How to get all keys from Ordered Dictionary?

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

Upvotes: 16

Views: 44710

Answers (3)

KasperGL
KasperGL

Reputation: 607

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?

Upvotes: 8

arshovon
arshovon

Reputation: 13651

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

Upvotes: 25

&#211;scar L&#243;pez
&#211;scar L&#243;pez

Reputation: 236034

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.

Upvotes: 6

Related Questions