How to Unpack Dictionaries and Lists in Python
Destructuring (also known as unpacking) in Python allows you to extract values from data structures like dictionaries and lists into individual variables in a concise and readable way.
This guide explains how to destructure dictionaries and lists, covering common use cases and best practices.
Destructuring Dictionaries
Directly unpacking a dictionary in an assignment statement unpacks its keys, not its values:
my_dict = {
'first': 'tom',
'last': 'nolan',
'site': 'tutorialreference.com'
}
a, b, c = my_dict # Unpacks KEYS, not values
print(a) # Output: first
print(b) # Output: last
print(c) # Output: site
- The example will unpack the keys in the order in which they have been added.
Getting Dictionary Values with .values()
To unpack the values of a dictionary, use the .values()
method:
my_dict = {
'first': 'tom',
'last': 'nolan',
'site': 'tutorialreference.com'
}
first, last, site = my_dict.values() # Unpack the VALUES
print(first) # Output: tom
print(last) # Output: nolan
print(site) # Output: tutorialreference.com
- The number of variables must match the number of values.
Getting Key-Value Pairs with .items()
To unpack both keys and values, use the .items()
method (most useful within a loop, covered later):
my_dict = {
'first': 'tom',
'last': 'nolan',
'site': 'tutorialreference.com'
}
print(my_dict.items()) # Output: dict_items([('first', 'tom'), ('last', 'nolan'), ('site', 'tutorialreference.com')])
Handling Missing Keys with .get()
If you're unsure whether a key exists, using direct access (my_dict['key']
) will raise a KeyError
if the key is missing. Use .get()
with a default value to handle this gracefully:
my_dict = {
'first': 'tom',
'last': 'nolan',
'site': 'tutorialreference.com'
}
#This will throw an exception, better to use dict.get()
#first, second = my_dict['first'], my_dict['second']
first, second = my_dict.get('first'), my_dict.get('second', 'default_value')
print(first) # Output: tom
print(second) # Output: default_value (because 'second' key is missing)
operator.itemgetter()
from operator import itemgetter
my_dict = {
'first': 'tom',
'last': 'nolan',
'site': 'tutorialreference.com'
}
first, last, site = itemgetter('first', 'last', 'site')(my_dict)
print(first) # Output: tom
print(last) # Output: nolan
print(site) # Output: tutorialreference.com
- The
itemgetter
is useful when you need to get the same set of keys from a list of dictionaries. - This is less readable, and it throws a
KeyError
if the key doesn't exist.
Destructuring Lists
List (and tuple) unpacking is more common and straightforward than dictionary unpacking.
Basic List Unpacking
a_list = ['tutorial', 'reference', 'com']
a, b, c = a_list
print(a) # Output: tutorial
print(b) # Output: reference
print(c) # Output: com
- The number of variables must match the number of elements in the list.
Ignoring Values with _
Use the underscore (_
) to discard values you don't need:
a_list = ['tutorial', 'reference', 'com']
a, b, _ = a_list # Discard the last value
print(a) # Output: tutorial
print(b) # Output: reference
Gathering Remaining Values with *
Use a starred expression (*
) to collect multiple values into a single variable (as a list):
a_list = ['tutorial', 'reference', '.', 'com']
a, *b, c = a_list # a gets the first, c gets the last, b gets the rest
print(a) # Output: tutorial
print(b) # Output: ['reference', '.']
print(c) # Output: com
- The variable with
*
will store the middle values in a list. - There can only be a single variable with
*
on the left-hand side.
Nested Lists
Unpacking also works with nested lists:
a_list = ['tutorial', ['reference', '.', 'com']]
a, [b, c, d] = a_list # Nested unpacking
print(a) # Output: tutorial
print(b) # Output: reference
print(c) # Output: .
print(d) # Output: com
- The variables are extracted following the same structure as the original nested list.
Destructuring in for
Loops
Unpacking is particularly useful within for
loops:
a_list = ['tutorial', 'reference', '.', 'com']
for index, item in enumerate(a_list):
print(index, item)
# Output:
# 0 tutorial
# 1 reference
# 2 .
# 3 com
- The code loops through the elements and also extracts their index.