Last updated: Apr 11, 2024
Reading timeยท6 min
Note: if you need to destructure lists in Python, click on the second subheading.
To destructure dictionaries in Python:
dict.values()
method to get a view of the dictionary's values.a_dict = { 'first': 'bobby', 'last': 'hadz', 'site': 'bobbyhadz.com' } first, last, site = a_dict.values() print(first) # ๐๏ธ bobby print(last) # ๐๏ธ hadz print(site) # ๐๏ธ com
The dict.values() method returns a new view of the dictionary's values.
a_dict = { 'first': 'bobby', 'last': 'hadz', 'site': 'bobbyhadz.com' } # ๐๏ธ dict_values(['bobby', 'hadz', 'bobbyhadz.com']) print(a_dict.values()) first, last, site = a_dict.values() print(first) # ๐๏ธ bobby print(last) # ๐๏ธ hadz print(site) # ๐๏ธ com
If you directly destructure without using dict.values()
, you would assign the
keys of the dictionary to variables.
a_dict = { 'first': 'bobby', 'last': 'hadz', 'site': 'bobbyhadz.com' } a, b, c = a_dict print(a) # ๐๏ธ first print(b) # ๐๏ธ last print(c) # ๐๏ธ site
dict
class is guaranteed to preserve the insertion order.Make sure the variables on the left are exactly as many as the values in the dictionary, otherwise, an error is raised.
operator.itemgetter
You can also use the operator.itemgetter() class to destructure dictionaries.
from operator import itemgetter a_dict = { 'first': 'bobby', 'last': 'hadz', 'site': 'bobbyhadz.com' } first, last, site = itemgetter('first', 'last', 'site')(a_dict) print(first) # ๐๏ธ bobby print(last) # ๐๏ธ hadz print(site) # ๐๏ธ com
The operator.itemgetter()
class returns a callable object that fetches the
items at the specified keys.
For example, x = itemgetter('key')
and then calling x(my_dict)
, returns
my_dict['key']
.
x = itemgetter('key1', 'key2', 'key3')
and then calling x(my_dict)
returns (my_dict['key1'], my_dict['key2'], my_dict['key3'])
.When multiple keys are specified, the itemgetter()
class returns a tuple
containing the values of the keys.
You can also only do this for certain dictionary keys.
from operator import itemgetter a_dict = { 'first': 'bobby', 'last': 'hadz', 'site': 'bobbyhadz.com' } first, last = itemgetter('first', 'last')(a_dict) print(first) # ๐๏ธ bobby print(last) # ๐๏ธ hadz
Make sure the variables on the left-hand side of the assignment are exactly as
many as the keys you've passed to the itemgetter()
class.
If you have to destructure dictionaries often, you can also create a reusable function.
a_dict = { 'first': 'bobby', 'last': 'hadz', 'site': 'bobbyhadz.com' } def pluck(dictionary, *keys): return (dictionary[key] for key in keys) first, last = pluck(a_dict, 'first', 'last') print(first) # ๐๏ธ bobby print(last) # ๐๏ธ hadz
The pluck()
function takes a dictionary and one or more keys and returns a
tuple containing the corresponding values.
You can then destructure the keys from the tuple.
Here is an equivalent example without using a function.
a_dict = { 'first': 'bobby', 'last': 'hadz', 'site': 'bobbyhadz.com' } first, last = (a_dict[key] for key in ('first', 'last')) print(first) # ๐๏ธ bobby print(last) # ๐๏ธ hadz
The generator expression iterates over the tuple of keys and on each iteration, we return the corresponding value.
You can also directly destructure dictionaries in Python.
a_dict = { 'first': 'bobby', 'last': 'hadz', 'site': 'bobbyhadz.com' } first, last = a_dict['first'], a_dict['last'] print(first) # ๐๏ธ bobby print(last) # ๐๏ธ hadz
The syntax is quite verbose, but the benefit of doing this is that you can also use the dict.get() method.
If a key doesn't exist and you use the square brackets syntax, you'd get a KeyError exception.
a_dict = { 'first': 'bobby', 'last': 'hadz', 'site': 'bobbyhadz.com' } # โ๏ธ KeyError: 'second' first, second = a_dict['first'], a_dict['second']
However, if you use the dict.get()
method, None
is returned for non-existent
keys by default.
a_dict = { 'first': 'bobby', 'last': 'hadz', 'site': 'bobbyhadz.com' } first, second = a_dict.get('first'), a_dict.get('second') print(first) # ๐๏ธ bobby print(second) # ๐๏ธ None
You can also pass a second argument to the dict.get()
method if you want to
supply a different default value when the key doesn't exist.
a_dict = { 'first': 'bobby', 'last': 'hadz', 'site': 'bobbyhadz.com' } first, second = a_dict.get('first', 'def val'), a_dict.get('second', 'def val') print(first) # ๐๏ธ bobby print(second) # ๐๏ธ def val
The dict.get
method returns the value for the given key if the key is in the
dictionary, otherwise a default value is returned.
The method takes the following 2 parameters:
Name | Description |
---|---|
key | The key for which to return the value |
default | The default value to be returned if the provided key is not present in the dictionary (optional) |
default
parameter is not provided, it defaults to None
, so the get()
method never raises a KeyError
.You can also destructure dictionaries in for
loops.
a_dict = { 'first': 'bobby', 'last': 'hadz', 'site': 'bobbyhadz.com' } for key, value in a_dict.items(): # first bobby # last hadz # site bobbyhadz.com print(key, value)
The dict.items() method returns a new view of the dictionary's items ((key, value) pairs).
a_dict = { 'first': 'bobby', 'last': 'hadz', 'site': 'bobbyhadz.com' } # dict_items([('first', 'bobby'), ('last', 'hadz'), ('site', 'bobbyhadz.com')]) print(a_dict.items())
On each iteration, we assign the key to the key
variable and the value to the
value
variable.
One way to destructure a list is to declare exactly as many variables on the left as there are items in the list.
a_list = ['bobby', 'hadz', 'com'] a, b, c = a_list print(a) # ๐๏ธ bobby print(b) # ๐๏ธ hadz print(c) # ๐๏ธ com
If your list contains sublists, then you have to reflect that in the assignment on the left-hand side.
a_list = ['bobby', ['hadz', '.', 'com']] a, [b, c, d] = a_list print(a) # ๐๏ธ bobby print(b) # ๐๏ธ hadz print(c) # ๐๏ธ . print(d) # ๐๏ธ com
However, when using this approach, you have to declare exactly as many variables as the items in the list.
This is very often not what you want.
You can use an underscore _
character to discard an item that is not needed.
a_list = ['bobby', 'hadz', '.', 'com'] a, b, _, c = a_list print(a) # ๐๏ธ bobby print(b) # ๐๏ธ hadz print(c) # ๐๏ธ com
The c
variable stores the string com
because we used an underscore _
to
discard the period .
.
You can use as many underscores as necessary in the assignment, as long as the variables that are declared on the left are exactly as many as the items in the list.
a_list = ['bobby', 'hadz', '.', 'com'] a, _, _, b = a_list print(a) # ๐๏ธ bobby print(b) # ๐๏ธ com
*
to gather itemsYou can also use an asterisk when you need to gather multiple items into a single variable.
a_list = ['bobby', 'hadz', '.', 'com'] a, *b, c = a_list print(a) # ๐๏ธ bobby print(b) # ๐๏ธ ['hadz', '.'] print(c) # ๐๏ธ com
The b
variable is a list that contains all of the list items in the middle
(all list items except the first and the last).
The asterisk *
character can also be used to gather the remaining list items
after you've selected the ones you want to destructure.
a_list = ['bobby', 'hadz', '.', 'com'] a, b, *c = a_list print(a) # ๐๏ธ bobby print(b) # ๐๏ธ hadz print(c) # ๐๏ธ ['.', 'com']
In cases where you don't need the remaining items, use an underscore for the name of the variable.
a_list = ['bobby', 'hadz', '.', 'com'] a, b, *_ = a_list print(a) # ๐๏ธ bobby print(b) # ๐๏ธ hadz
The a
and b
variables store the first two list items and the rest are stored
in the _
variable.
The asterisk syntax is quite flexible and can be used to gather the first N, the middle N or the last N list items.
a_list = ['bobby', 'hadz', '.', 'com'] *first_n, last = a_list print(first_n) # ๐๏ธ ['bobby', 'hadz', '.'] print(last) # ๐๏ธ com
The first_n
variable stores all list items but the last.
You can also destructure lists in for
loops.
a_list = ['bobby', 'hadz', '.', 'com'] for item, index in enumerate(a_list): # 0 bobby # 1 hadz # 2 . # 3 com print(item, index)
The enumerate() function takes an iterable and returns an enumerate object containing tuples where the first element is the index and the second is the item.
a_list = ['bobby', 'hadz', '.', 'com'] # [(0, 'bobby'), (1, 'hadz'), (2, '.'), (3, 'com')] print(list(enumerate(a_list)))
On each iteration, we assign the current list item to the item
variable and
the index to the index
variable.
You can learn more about the related topics by checking out the following tutorials: