How to destructure Dictionaries and Lists in Python

avatar
Borislav Hadzhiev

Last updated: Apr 11, 2024
6 min

banner

# Table of Contents

  1. How to destructure Dictionaries in Python
  2. How to destructure Lists in Python

Note: if you need to destructure lists in Python, click on the second subheading.

# How to destructure Dictionaries in Python

To destructure dictionaries in Python:

  1. Call the dict.values() method to get a view of the dictionary's values.
  2. Assign the results to variables.
main.py
a_dict = { 'first': 'bobby', 'last': 'hadz', 'site': 'bobbyhadz.com' } first, last, site = a_dict.values() print(first) # ๐Ÿ‘‰๏ธ bobby print(last) # ๐Ÿ‘‰๏ธ hadz print(site) # ๐Ÿ‘‰๏ธ com

destructuring dictionaries in python

The code for this article is available on GitHub

The dict.values() method returns a new view of the dictionary's values.

main.py
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

destructuring dictionaries with operator itemgetter

If you directly destructure without using dict.values(), you would assign the keys of the dictionary to variables.

main.py
a_dict = { 'first': 'bobby', 'last': 'hadz', 'site': 'bobbyhadz.com' } a, b, c = a_dict print(a) # ๐Ÿ‘‰๏ธ first print(b) # ๐Ÿ‘‰๏ธ last print(c) # ๐Ÿ‘‰๏ธ site
As of Python 3.7, the standard 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.

# Destructuring dictionaries with operator.itemgetter

You can also use the operator.itemgetter() class to destructure dictionaries.

main.py
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 code for this article is available on GitHub

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

Similarly, 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.

main.py
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.

# Destructuring dictionaries with a reusable function

If you have to destructure dictionaries often, you can also create a reusable function.

main.py
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 code for this article is available on GitHub

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.

main.py
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.

# Destructuring dictionaries directly in Python

You can also directly destructure dictionaries in Python.

main.py
a_dict = { 'first': 'bobby', 'last': 'hadz', 'site': 'bobbyhadz.com' } first, last = a_dict['first'], a_dict['last'] print(first) # ๐Ÿ‘‰๏ธ bobby print(last) # ๐Ÿ‘‰๏ธ hadz
The code for this article is available on GitHub

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.

main.py
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.

main.py
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.

main.py
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:

NameDescription
keyThe key for which to return the value
defaultThe default value to be returned if the provided key is not present in the dictionary (optional)
If a value for the default parameter is not provided, it defaults to None, so the get() method never raises a KeyError.

# Destructuring dictionaries in for loops

You can also destructure dictionaries in for loops.

main.py
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 code for this article is available on GitHub

The dict.items() method returns a new view of the dictionary's items ((key, value) pairs).

main.py
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.

# How to destructure Lists in Python

One way to destructure a list is to declare exactly as many variables on the left as there are items in the list.

main.py
a_list = ['bobby', 'hadz', 'com'] a, b, c = a_list print(a) # ๐Ÿ‘‰๏ธ bobby print(b) # ๐Ÿ‘‰๏ธ hadz print(c) # ๐Ÿ‘‰๏ธ com
The code for this article is available on GitHub

If your list contains sublists, then you have to reflect that in the assignment on the left-hand side.

main.py
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.

# Using underscores to discard items

You can use an underscore _ character to discard an item that is not needed.

main.py
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.

main.py
a_list = ['bobby', 'hadz', '.', 'com'] a, _, _, b = a_list print(a) # ๐Ÿ‘‰๏ธ bobby print(b) # ๐Ÿ‘‰๏ธ com

# Using an asterisk * to gather items

You can also use an asterisk when you need to gather multiple items into a single variable.

main.py
a_list = ['bobby', 'hadz', '.', 'com'] a, *b, c = a_list print(a) # ๐Ÿ‘‰๏ธ bobby print(b) # ๐Ÿ‘‰๏ธ ['hadz', '.'] print(c) # ๐Ÿ‘‰๏ธ com
The code for this article is available on GitHub

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.

main.py
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.

main.py
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.

main.py
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.

# Destructuring lists in for loops

You can also destructure lists in for loops.

main.py
a_list = ['bobby', 'hadz', '.', 'com'] for item, index in enumerate(a_list): # 0 bobby # 1 hadz # 2 . # 3 com print(item, index)
The code for this article is available on GitHub

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.

main.py
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.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.

Copyright ยฉ 2024 Borislav Hadzhiev