How do you retrieve items from a dictionary in the order that they're inserted?
The standard Python dict
does this by default if you're using CPython 3.6+ (or Python 3.7+ for any other implementation of Python).
On older versions of Python you can use collections.OrderedDict
.
Python: iterating through a dict in the order in which items were inserted
You shouldn't convert your dict
to an OrderedDict
, you should be using an OrderedDict
in the first place:
from collections import OrderedDict
od = OrderedDict()
od['c'] = 1
od['f'] = 2
od['a'] = 3
Or often easier, create the OrderedDict
from a list
of tuples or a tuple
of tuples
:
od = OrderedDict([('c', 1), ('f', 2), ('a', 3)])
The problem with converting a dict
to an OrderedDict
is that as soon as you create a dict
or add anything into it, the order is lost. So you can't use a dict
at all if you need to keep the order.
Why dictionary values aren't in the inserted order?
Dictionaries in Python are unordered by definition. Use OrderedDict
if you need the order in which values were inserted (it's available in Python 2.7 and 3.x).
How to access the first and the last elements in a dictionary?
Use an OrderedDict
, because a normal dictionary doesn't preserve the insertion order of its elements when traversing it. Here's how:
# import the right class
from collections import OrderedDict
# create and fill the dictionary
d = OrderedDict()
d['first'] = 1
d['second'] = 2
d['third'] = 3
# retrieve key/value pairs
els = list(d.items()) # explicitly convert to a list, in case it's Python 3.x
# get first inserted element
els[0]
=> ('first', 1)
# get last inserted element
els[-1]
=> ('third', 3)
Order of keys in dictionaries in old versions of Python
You could use OrderedDict (requires Python 2.7) or higher.
Also, note that OrderedDict({'a': 1, 'b':2, 'c':3})
won't work since the dict
you create with {...}
has already forgotten the order of the elements. Instead, you want to use OrderedDict([('a', 1), ('b', 2), ('c', 3)])
.
As mentioned in the documentation, for versions lower than Python 2.7, you can use this recipe.
Why items order in a dictionary changed in Python?
May I know why this is happening?
It is because of the way dicts are organized internally.
In short, this works via a hash-table which puts the keys into buckets according to their hash()
value.
If I use dict.keys() to extract the keys from a dictionary and iterate it in an order that I suppose it to be, will that cause dismatch problem?
Depending on how you do it.
k = list(d.keys())
k.sort()
for i in k: print i, d[i]
should exactly work how you want it to work.
How to maintain the order of an existing dictionary python
In Python 3.6, dictionaries are ordered internally, but this is considered an implementation detail which should not be relied upon.
In Python 3.7, dictionaries are ordered.
Therefore, you have 2 options:
Use the implementation detail at your risk
You can use list(d)
to retrieve the keys of the dictionary maintaining insertion order.
dirs_dictionary = {"user_dir_treatment":"/home/dataset_1/treatment",
"user_dir_control":"/home/dataset_1/control"}
empty_list = list(dirs_dictionary)
print(empty_list)
# ['user_dir_treatment', 'user_dir_control']
Use OrderedDict
from collections import OrderedDict
dirs_dictionary = OrderedDict([("user_dir_treatment", "/home/dataset_1/treatment"),
("user_dir_control", "/home/dataset_1/control")]
empty_list = list(dirs_dictionary)
print(empty_list)
# ['user_dir_treatment', 'user_dir_control']
Related Topics
How to Avoid Explicit 'Self' in Python
Python: Urlerror: <Urlopen Error [Errno 10060]
Is a Python Dictionary an Example of a Hash Table
Check If Item Is in an Array/List
Only Extracting Text from This Element, Not Its Children
Attributeerror: 'Tensor' Object Has No Attribute 'Numpy'
How to Create a View Onto a Numpy Array
How to Add a String in a Certain Position
Reading Unicode File Data with Bom Chars in Python
Postponing Functions in Python
Reading a Text File and Splitting It into Single Words in Python
How to Add an Integer to Each Element in a List
How to Create a Custom Activation Function with Keras