Last updated: Apr 9, 2024
Reading timeยท4 min
Use bracket notation to assign a dictionary value to a variable, e.g.
first = my_dict['first_name']
.
The left-hand side of the assignment is the variable's name and the right-hand side is the value.
my_dict = { 'first_name': 'Bobby', 'last_name': 'Hadz', 'site': 'bobbyhadz.com', } first = my_dict['first_name'] print(first) # ๐๏ธ Bobby first = list(my_dict.values())[0] print(first) # ๐๏ธ Bobby key = 'last_name' value = my_dict[key] print(value) # ๐๏ธ Hadz
The first example uses square brackets to access a dictionary key and assigns the corresponding value to a variable.
my_dict = { 'first_name': 'Bobby', 'last_name': 'Hadz', 'site': 'bobbyhadz.com', } first = my_dict['first_name'] print(first) # ๐๏ธ Bobby
If you need to access the
dictionary value using an index,
use the dict.values()
method.
my_dict = { 'first_name': 'Bobby', 'last_name': 'Hadz', 'site': 'bobbyhadz.com', } first = list(my_dict.values())[0] print(first) # ๐๏ธ Bobby
0
, and the last item has an index of -1
or len(my_list) - 1
.The dict.values() method returns a new view of the dictionary's values.
my_dict = { 'first_name': 'Bobby', 'last_name': 'Hadz', 'site': 'bobbyhadz.com', } # ๐๏ธ dict_values(['Bobby', 'Hadz', 'bobbyhadz.com']) print(my_dict.values())
We had to use the list() class to convert the view object to a list because view objects are not subscriptable (cannot be accessed at an index).
You can use the same approach if you have the key stored in a variable.
my_dict = { 'first_name': 'Bobby', 'last_name': 'Hadz', 'site': 'bobbyhadz.com', } key = 'last_name' value = my_dict[key] print(value) # ๐๏ธ Hadz
If you try to access a dictionary key that doesn't exist using square brackets,
you'd get a KeyError
.
my_dict = { 'first_name': 'Bobby', 'last_name': 'Hadz', 'site': 'bobbyhadz.com', } # โ๏ธ KeyError: 'first' first = my_dict['first']
On the other hand, the dict.get()
method
returns None for non-existent keys by default.
my_dict = { 'first_name': 'Bobby', 'last_name': 'Hadz', 'site': 'bobbyhadz.com', } first = my_dict.get('first_name') print(first) # ๐๏ธ Bobby first = my_dict.get('first') print(first) # ๐๏ธ None
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) |
If a value for the default
parameter is not provided, it defaults to None
,
so the get()
method never raises a KeyError
.
my_dict = { 'first_name': 'Bobby', 'last_name': 'Hadz', 'site': 'bobbyhadz.com', } print(my_dict.get('site')) # ๐๏ธ bobbyhadz.com print(my_dict.get('another')) # ๐๏ธ None print(my_dict.get('another', 'default value')) # ๐๏ธ default value
If you need to assign the key-value pairs of a dictionary to variables, update
the locals()
dictionary.
Update the locals()
dictionary to assign the key-value pairs of a dictionary
to variables.
my_dict = { 'first_name': 'Bobby', 'last_name': 'Hadz', 'site': 'bobbyhadz.com', } # โ Using locals() locals().update(my_dict) print(first_name) # ๐๏ธ Bobby print(site) # ๐๏ธ bobbyhadz.com # --------------------------------------- # โ Using exec (only if data is trusted) for key, value in my_dict.items(): exec(key + '=value') print(first_name) # ๐๏ธ Bobby print(site) # ๐๏ธ bobbyhadz.com
The first example uses the locals()
dictionary to assign the key-value pairs
of a dictionary to local variables.
The locals()
function returns a dictionary that contains the current scope's
local variables.
my_dict = { 'first_name': 'Bobby', 'last_name': 'Hadz', 'site': 'bobbyhadz.com', } # {'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x7fd512e25de0>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': '/home/borislav/Desktop/bobbyhadz_python/main.py', '__cached__': None, 'my_dict': {'first_name': 'Bobby', 'last_name': 'Hadz', 'site': 'bobbyhadz.com'}} print(locals())
The dict.update method updates the dictionary with the key-value pairs from the provided value.
my_dict = {'name': 'Alice'} # โ Pass dictionary to the update() method my_dict.update({'name': 'bobbyhadz', 'age': 30}) print(my_dict) # ๐๏ธ {'name': 'bobbyhadz', 'age': 30}
You can access the variables directly after calling the dict.update()
method.
my_dict = { 'first_name': 'Bobby', 'last_name': 'Hadz', 'site': 'bobbyhadz.com', } locals().update(my_dict) print(first_name) # ๐๏ธ Bobby print(site) # ๐๏ธ bobbyhadz.com
SimpleNamespace
class.from types import SimpleNamespace my_dict = { 'first_name': 'Bobby', 'last_name': 'Hadz', 'site': 'bobbyhadz.com', } namespace = SimpleNamespace(**my_dict) print(namespace.first_name) # ๐๏ธ Bobby print(namespace.site) # ๐๏ธ bobbyhadz.com
The SimpleNamespace class can be initialized with keyword arguments.
The keys of the dictionary are accessible as attributes on the namespace object.
Alternatively, you can use the exec()
function.
This is a three-step process:
exec()
function to assign each key-value pair to a variable.exec()
function supports dynamic execution of Python code.my_dict = { 'first_name': 'Bobby', 'last_name': 'Hadz', 'site': 'bobbyhadz.com', } for key, value in my_dict.items(): exec(key + '=value') print(first_name) # ๐๏ธ Bobby print(site) # ๐๏ธ bobbyhadz.com
The dict.items() method returns a new view of the dictionary's items ((key, value) pairs).
my_dict = { 'first_name': 'Bobby', 'last_name': 'Hadz', 'site': 'bobbyhadz.com', } # ๐๏ธ dict_items([('first_name', 'Bobby'), ('last_name', 'Hadz'), ('site', 'bobbyhadz.com')]) print(my_dict.items())
On each iteration, we use the exec()
function to assign the current key-value
pair to a variable.
exec()
function with untrusted user input.The exec() function supports dynamic execution of Python code.
The function takes a string, parses it as a suite of Python statements and runs the code.
Which approach you pick is a matter of personal preference. I'd go with the
SimpleNamespace
class to avoid any linting errors for trying to access
undefined variables.
You can learn more about the related topics by checking out the following tutorials: