Last updated: Apr 10, 2024
Reading timeยท12 min
To get the first element of an OrderedDict
:
iter()
function to create an iterator object from the
OrderedDict
.next()
function to get the first item of
the OrderedDict
.from collections import OrderedDict my_dict = OrderedDict( [('name', 'bobbyhadz'), ('age', 30), ('topic', 'Python')] ) first_key = next(iter(my_dict)) print(first_key) # ๐๏ธ name first_value = my_dict[first_key] print(first_value) # ๐๏ธ bobbyhadz first_pair = next(iter(my_dict.items())) print(first_pair) # ๐๏ธ ('name', 'bobbyhadz') print(list(my_dict.items())[0]) # ๐๏ธ ('name', 'bobbyhadz') print(list(my_dict.items())[1]) # ๐๏ธ ('age', 30)
The iter() function takes an object and constructs an iterator from it.
The next() function returns the next item from the provided iterator.
dict.items()
to the iter()
function if you need to get the first key-value pair of the OrderedDict
.from collections import OrderedDict my_dict = OrderedDict( [('name', 'bobbyhadz'), ('age', 30), ('topic', 'Python')] ) first_key = next(iter(my_dict)) print(first_key) # ๐๏ธ name first_value = my_dict[first_key] print(first_value) # ๐๏ธ bobbyhadz first_pair = next(iter(my_dict.items())) print(first_pair) # ๐๏ธ ('name', 'bobbyhadz')
The dict.items() method returns a new view of the dictionary's items ((key, value) pairs).
from collections import OrderedDict my_dict = OrderedDict( [('name', 'bobbyhadz'), ('age', 30), ('topic', 'Python')] ) # ๐๏ธ odict_items([('name', 'bobbyhadz'), ('age', 30), ('topic', 'Python')]) print(my_dict.items())
You can convert the view object to a list if you need to access a specific index
in the OrderedDict
.
from collections import OrderedDict my_dict = OrderedDict( [('name', 'bobbyhadz'), ('age', 30), ('topic', 'Python')] ) print(list(my_dict.items())[0]) # ๐๏ธ ('name', 'bobbyhadz') print(list(my_dict.items())[1]) # ๐๏ธ ('age', 30)
You can use the reversed()
method if you need to get the last element in an
OrderedDict
.
from collections import OrderedDict my_dict = OrderedDict( [('name', 'bobbyhadz'), ('age', 30), ('topic', 'Python')] ) last_key = next(reversed(my_dict)) print(last_key) # ๐๏ธ topic last_value = my_dict[last_key] print(last_value) # ๐๏ธ Python last_pair = next(reversed(my_dict.items())) print(last_pair) # ๐๏ธ ('topic', 'Python')
The reversed function takes an iterator, reverses it and returns the result.
from collections import OrderedDict my_dict = OrderedDict( [('name', 'bobbyhadz'), ('age', 30), ('topic', 'Python')] ) # ๐๏ธ ['topic', 'age', 'name'] print(list(reversed(my_dict)))
Note that the next()
function can be passed a default value as the second
argument.
from collections import OrderedDict my_dict = OrderedDict() first_pair = next(iter(my_dict.items()), None) print(first_pair) # ๐๏ธ None if first_pair is not None: print('Do work')
If the iterator is exhausted or empty, the default value is returned.
StopIteration
exception is raised.You can also use a basic for loop to get the
first item of an OrderedDict
.
This is a three-step process:
for
loop to iterate over the OrderedDict
.break
statement to exit out of the loop on the first iteration.from collections import OrderedDict my_dict = OrderedDict( [('name', 'bobbyhadz'), ('age', 30), ('topic', 'Python')] ) for key in my_dict: print(key) # ๐๏ธ name print(my_dict[key]) # ๐๏ธ bobbyhadz break
We used a for
loop to iterate over the OrderedDict
once.
The break statement breaks out of the
innermost enclosing for
or while
loop.
After we get the first key-value pair of the OrderedDict
, we exit the for
loop.
The
OrderedDict
class is a subclass of dict
that remembers the order in which its entries were
added.
Note that as of Python 3.7, the standard dict
class is guaranteed to preserve
the insertion order as well.
To get the last element of an OrderedDict
:
reversed()
function to reverse the OrderedDict
object.next()
function to get the last element of the
OrderedDict
.from collections import OrderedDict my_dict = OrderedDict( [('id', 1), ('name', 'bobbyhadz'), ('topic', 'Python')] ) last_key = next(reversed(my_dict)) print(last_key) # ๐๏ธ topic last_value = my_dict[last_key] print(last_value) # ๐๏ธ Python last_pair = next(reversed(my_dict.items())) print(last_pair) # ๐๏ธ ('topic', 'Python')
The reversed() function takes an iterator, reverses it and returns the result.
from collections import OrderedDict my_dict = OrderedDict( [('id', 1), ('name', 'bobbyhadz'), ('topic', 'Python')] ) # ๐๏ธ ['topic', 'name', 'id'] print(list(reversed(my_dict)))
The next() function returns the next item from the provided iterator.
from collections import OrderedDict my_dict = OrderedDict( [('id', 1), ('name', 'bobbyhadz'), ('topic', 'Python')] ) last_key = next(reversed(my_dict)) print(last_key) # ๐๏ธ topic last_value = my_dict[last_key] print(last_value) # ๐๏ธ Python last_pair = next(reversed(my_dict.items())) print(last_pair) # ๐๏ธ ('topic', 'Python')
You can pass the result of calling the dict.items()
method to the reversed()
function to
get the last key-value pair of the
OrderedDict
.
The dict.items method returns a new view of the dictionary's items ((key, value) pairs).
from collections import OrderedDict my_dict = OrderedDict( [('id', 1), ('name', 'bobbyhadz'), ('topic', 'Python')] ) # ๐๏ธ odict_items([('id', 1), ('name', 'bobbyhadz'), ('topic', 'Python')]) print(my_dict.items())
You can convert the view object to a list if you need to access a specific index
in the OrderedDict
.
from collections import OrderedDict my_dict = OrderedDict( [('id', 1), ('name', 'bobbyhadz'), ('topic', 'Python')] ) print(list(my_dict.items())[0]) # ๐๏ธ ('id', 1) print(list(my_dict.items())[1]) # ๐๏ธ ('name', 'bobbyhadz')
You can use the same approach to get the first element in an OrderedDict
.
from collections import OrderedDict my_dict = OrderedDict( [('id', 1), ('name', 'bobbyhadz'), ('topic', 'Python')] ) first_key = next(iter(my_dict)) print(first_key) # ๐๏ธ id first_value = my_dict[first_key] print(first_value) # ๐๏ธ 1 first_pair = next(iter(my_dict.items())) print(first_pair) # ๐๏ธ ('id', 1)
We used the iter() function to get an iterator object.
next()
function can be passed a default value as the second argument.from collections import OrderedDict my_dict = OrderedDict() last_key = next(reversed(my_dict), 'default value') print(last_key) # ๐๏ธ default value
If the iterator is exhausted or empty, the default value is returned.
If the iterator is exhausted or empty and no default value is provided, a
StopIteration
exception is raised.
OrderedDict
might be empty, you could supply a default value of None
if you need to avoid the StopIteration
exception.from collections import OrderedDict my_dict = OrderedDict() last_pair = next(reversed(my_dict.items()), None) print(last_pair) # ๐๏ธ None if last_pair is not None: print('Do work')
The
OrderedDict
class is a subclass of dict
that remembers the order in which its entries were
added.
Note that as of Python 3.7, the standard dict
class is guaranteed to preserve
the insertion order as well.
To get all keys in an OrderedDict()
as a list:
dict.keys()
method to get a view object of the keys in the
OrderedDict
.list()
class to convert the view object to a list.from collections import OrderedDict my_dict = OrderedDict( [('first', 'bobby'), ('last', 'hadz'), ('age', 30)] ) all_keys = list(my_dict.keys()) print(all_keys) # ๐๏ธ ['first', 'last', 'age'] all_values = list(my_dict.values()) print(all_values) # ๐๏ธ ['bobby', 'hadz', 30] all_items = list(my_dict.items()) # ๐๏ธ [('first', 'bobby'), ('last', 'hadz'), ('age', 30)] print(all_items)
The dict.keys() method returns a new view of the dictionary's keys.
dict.keys()
method returns a view object, so we used the list()
class to convert the view to a list.This is necessary if you need to access specific keys by index.
from collections import OrderedDict my_dict = OrderedDict( [('first', 'bobby'), ('last', 'hadz'), ('age', 30)] ) all_keys = list(my_dict.keys()) print(all_keys) # ๐๏ธ ['first', 'last', 'age'] print(all_keys[0]) # ๐๏ธ first print(all_keys[1]) # ๐๏ธ last
You can use the dict.values()
method if you need to get all values in the
OrderedDict
as a list.
from collections import OrderedDict my_dict = OrderedDict( [('first', 'bobby'), ('last', 'hadz'), ('age', 30)] ) all_values = list(my_dict.values()) print(all_values) # ๐๏ธ ['bobby', 'hadz', 30] print(all_values[0]) # ๐๏ธ bobby print(all_values[1]) # ๐๏ธ hadz
The dict.values method returns a new view of the dictionary's values.
dict.items()
method if you need to get all key-value pairs in the OrderedDict
as a list.from collections import OrderedDict my_dict = OrderedDict( [('first', 'bobby'), ('last', 'hadz'), ('age', 30)] ) all_items = list(my_dict.items()) # ๐๏ธ [('first', 'bobby'), ('last', 'hadz'), ('age', 30)] print(all_items) print(all_items[0]) # ๐๏ธ ('first', 'bobby') print(all_items[0][0]) # ๐๏ธ first print(all_items[0][1]) # ๐๏ธ bobby
The dict.items() method returns a new view of the dictionary's items ((key, value) pairs).
You can also use list slicing if you need to get a slice of the keys, values or items in the dictionary.
from collections import OrderedDict my_dict = OrderedDict( [('first', 'bobby'), ('last', 'hadz'), ('age', 30)] ) all_keys = list(my_dict.keys()) print(all_keys) # ๐๏ธ ['first', 'last', 'age'] first_2 = all_keys[:2] print(first_2) # ๐๏ธ ['first', 'last']
The syntax for list slicing is my_list[start:stop:step]
.
The start
index is inclusive and the stop
index is exclusive (up to, but not
including).
If the start
index is omitted, it is considered to be 0
, if the stop
index
is omitted, the slice goes to the end of the list.
0
, and the last item has an index of -1
or len(my_list) - 1
.The
OrderedDict
class is a subclass of dict
that remembers the order in which its entries were
added.
Note that as of Python 3.7, the standard dict
class is guaranteed to preserve
the insertion order as well.
To access items in an OrderedDict
by index:
dict.items()
method to get a view of the dictionary's items.list()
class to convert the view object to a list.from collections import OrderedDict my_dict = OrderedDict( [('name', 'bobbyhadz'), ('age', 30), ('topic', 'Python')] ) dict_items = list(my_dict.items()) # ๐๏ธ [('name', 'bobbyhadz'), ('age', 30), ('topic', 'Python')] print(dict_items) print(dict_items[0]) # ๐๏ธ ('name', 'bobbyhadz') print(dict_items[0][0]) # ๐๏ธ name print(dict_items[0][1]) # ๐๏ธ bobbyhadz
The dict.items() method returns a new view of the dictionary's items ((key, value) pairs).
from collections import OrderedDict my_dict = OrderedDict( [('name', 'bobbyhadz'), ('age', 30), ('topic', 'Python')] ) # ๐๏ธ odict_items([('name', 'bobbyhadz'), ('age', 30), ('topic', 'Python')]) print(my_dict.items())
Once we have a list of the items of the OrderedDict
, we can access the list at
a specific index.
from collections import OrderedDict my_dict = OrderedDict( [('name', 'bobbyhadz'), ('age', 30), ('topic', 'Python')] ) dict_items = list(my_dict.items()) print(dict_items[0]) # ๐๏ธ ('name', 'bobbyhadz') print(dict_items[0][0]) # ๐๏ธ name print(dict_items[0][1]) # ๐๏ธ bobbyhadz
0
, and the last item has an index of -1
or len(my_list) - 1
.You can also use the dict.keys()
or dict.values()
method if you only need to
access a key or a value at a specific index.
from collections import OrderedDict my_dict = OrderedDict( [('name', 'bobbyhadz'), ('age', 30), ('topic', 'Python')] ) dict_keys = list(my_dict.keys()) print(dict_keys) # ๐๏ธ ['name', 'age', 'topic'] print(dict_keys[1]) # ๐๏ธ age dict_values = list(my_dict.values()) print(dict_values) # ๐๏ธ ['bobbyhadz', 30, 'Python'] print(dict_values[1]) # ๐๏ธ 30
The dict.keys() method returns a new view of the dictionary's keys.
The dict.values() method returns a new view of the dictionary's values.
You can use the list.index()
method if you need to get the index of a specific
key in the OrderedDict
.
from collections import OrderedDict my_dict = OrderedDict( [('name', 'bobbyhadz'), ('age', 30), ('topic', 'Python')] ) dict_keys = list(my_dict.keys()) index = dict_keys.index('topic') print(index) # ๐๏ธ 2 dict_values = list(my_dict.values()) print(dict_values[index]) # ๐๏ธ Python
The list.index()
method returns the index of the first item whose value is
equal to the provided argument.
You can use list slicing if you need to get a slice of the dictionary's items.
from collections import OrderedDict my_dict = OrderedDict( [('name', 'bobbyhadz'), ('age', 30), ('topic', 'Python')] ) dict_items = list(my_dict.items()) # ๐๏ธ [('name', 'bobbyhadz'), ('age', 30), ('topic', 'Python')] print(dict_items) first_2 = dict_items[:2] print(first_2) # ๐๏ธ [('name', 'bobbyhadz'), ('age', 30)]
The syntax for list slicing is my_list[start:stop:step]
.
The start
index is inclusive and the stop
index is exclusive (up to, but not
including).
start
index is omitted, it is considered to be 0
, if the stop
index is omitted, the slice goes to the end of the list.The
OrderedDict
class is a subclass of dict
that remembers the order in which its entries were
added.
Note that as of Python 3.7, the standard dict
class is guaranteed to preserve
the insertion order as well.
To merge two OrderedDict
objects:
dict.items()
method to get a view of the items of the objects.list()
class to convert the view objects to lists.OrderedDict()
class.from collections import OrderedDict od1 = OrderedDict([('first', 'bobby')]) od2 = OrderedDict([('last', 'hadz'), ('age', 30)]) od3 = OrderedDict(list(od1.items()) + list(od2.items())) # ๐๏ธ OrderedDict([('first', 'bobby'), ('last', 'hadz'), ('age', 30)]) print(od3)
We used the dict.items()
method to get a view of the items of the
OrderedDict
objects
from collections import OrderedDict od1 = OrderedDict([('first', 'bobby')]) # ๐๏ธ odict_items([('first', 'bobby')]) print(od1.items()) od2 = OrderedDict([('last', 'hadz'), ('age', 30)]) # ๐๏ธ odict_items([('last', 'hadz'), ('age', 30)]) print(od2.items())
The dict.items method returns a new view of the dictionary's items ((key, value) pairs).
However, we can't use the addition (+) operator to combine view objects, so we had to convert them to lists.
# ๐๏ธ [('first', 'bobby'), ('last', 'hadz')] print([('first', 'bobby')] + [('last', 'hadz')])
The last step is to pass the list of key-value pairs to the OrderedDict
class.
from collections import OrderedDict od1 = OrderedDict([('first', 'bobby')]) od2 = OrderedDict([('last', 'hadz'), ('age', 30)]) od3 = OrderedDict(list(od1.items()) + list(od2.items())) # ๐๏ธ OrderedDict([('first', 'bobby'), ('last', 'hadz'), ('age', 30)]) print(od3)
Alternatively, you can use the dict.update()
method.
from collections import OrderedDict od1 = OrderedDict([('first', 'bobby')]) od2 = OrderedDict([('last', 'hadz'), ('age', 30)]) od1.update(od2) # ๐๏ธ OrderedDict([('first', 'bobby'), ('last', 'hadz'), ('age', 30)]) print(od1)
The dict.update method updates the dictionary with the key-value pairs from the provided value.
my_dict = {'name': 'Alice'} my_dict.update({'name': 'bobbyhadz', 'age': 30}) print(my_dict) # ๐๏ธ {'name': 'bobbyhadz', 'age': 30}
The method overrides the dictionary's existing keys and returns None.
This approach updates the first OrderedDict
in place.
The
OrderedDict
class is a subclass of dict
that remembers the order in which its entries were
added.
Note that as of Python 3.7, the standard dict
class is guaranteed to preserve
the insertion order as well.
To get the index of a key or a value in an OrderedDict
:
dict.keys()
or dict.values()
methods to get a view of the
dictionary's keys or values.list()
class to convert the view to a list.list.index()
method to get the index of the key or value.from collections import OrderedDict my_dict = OrderedDict( [('name', 'bobbyhadz'), ('age', 30), ('topic', 'Python')] ) # โ Get index of key in an OrderedDict dict_keys = list(my_dict.keys()) print(dict_keys) # ๐๏ธ ['name', 'age', 'topic'] index = dict_keys.index('age') print(index) # ๐๏ธ 1 # ----------------------------------------- # โ Get the index of a value in an OrderedDict value = 'Python' dict_values = list(my_dict.values()) print(dict_values) # ๐๏ธ ['bobbyhadz', 30, 'Python'] index = dict_values.index('Python') print(index) # ๐๏ธ 2
We used the dict.keys()
and dict.values()
methods to get a view of the
dictionary's keys and values.
list.index()
method on a view object, so we had to convert the objects to lists.The list.index()
method returns the index of the first item whose value is
equal to the provided argument.
The method raises a ValueError
if there is no such item in the list.
You can use a try/except statement if you need to handle the error.
from collections import OrderedDict my_dict = OrderedDict( [('name', 'bobbyhadz'), ('age', 30), ('topic', 'Python')] ) dict_keys = list(my_dict.keys()) print(dict_keys) # ๐๏ธ ['name', 'age', 'topic'] try: index = dict_keys.index('another') except ValueError: # ๐๏ธ This runs print('The specific key not is not in the OrderedDict')
You can use the dict.items()
method if you need to get a key-value pair of the
OrderedDict
by index.
from collections import OrderedDict my_dict = OrderedDict( [('name', 'bobbyhadz'), ('age', 30), ('topic', 'Python')] ) dict_items = list(my_dict.items()) # ๐๏ธ [('name', 'bobbyhadz'), ('age', 30), ('topic', 'Python')] print(dict_items) print(dict_items[0]) # ๐๏ธ ('name', 'bobbyhadz') print(dict_items[0][0]) # ๐๏ธ name print(dict_items[0][1]) # ๐๏ธ bobbyhadz
The dict.items() method returns a new view of the dictionary's items ((key, value) pairs).
You can use list slicing if you need to get a slice of the list.
from collections import OrderedDict my_dict = OrderedDict( [('name', 'bobbyhadz'), ('age', 30), ('topic', 'Python')] ) dict_items = list(my_dict.items()) # ๐๏ธ [('name', 'bobbyhadz'), ('age', 30), ('topic', 'Python')] print(dict_items) print(dict_items[1:3]) # ๐๏ธ [('age', 30), ('topic', 'Python')]
The syntax for list slicing is my_list[start:stop:step]
.
start
index is inclusive and the stop
index is exclusive (up to, but not including).If the start
index is omitted, it is considered to be 0
, if the stop
index
is omitted, the slice goes to the end of the list.
Python indexes are zero-based, so the first item in a list has an index of 0
,
and the last item has an index of -1
or len(my_list) - 1
.
The
OrderedDict
class is a subclass of dict
that remembers the order in which its entries were
added.
Note that as of Python 3.7, the standard dict
class is guaranteed to preserve
the insertion order as well.
I've also written an article on how to convert an OrderedDict to a regular Dict or List.