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
The methods dict. keys() and dict. values() return lists of the keys or values explicitly. There's also an items() which returns a list of (key, value) tuples, which is the most efficient way to examine all the key value data in the dictionary.
Using dictionary. The built-in Python method items() is used to retrieve all the keys and corresponding values. We can print the dictionary's keys and values by combining the items() method with a for loop. This method is more practical if you wish to print keys one at a time.
The dict.keys() method in Python Dictionary, returns a view object that displays a list of all the keys in the dictionary in order of insertion.
First, sort the keys alphabetically using key_value. iterkeys() function. Second, sort the keys alphabetically using the sorted (key_value) function & print the value corresponding to it.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With