Last updated: Apr 9, 2024
Reading timeยท4 min
Use square brackets to access a dictionary key using a variable, e.g.
my_dict[variable]
.
If the variable is an integer and the dictionary's keys are strings, convert
the variable to a string when accessing a key, e.g. my_dict[str(variable)]
.
# ๐๏ธ keys are strings my_dict = { '1': 'bobby', '2': 'hadz' } # ๐๏ธ variable is an integer variable = 1 print(my_dict[str(variable)]) # ๐๏ธ bobby
We used bracket notation to access a dictionary using a variable as the key.
If the dictionary's keys are strings and the variable is an integer, use the str() class to convert the variable to a string.
my_dict = { '1': 'bobby', '2': 'hadz' } variable = 1 print(my_dict[str(variable)]) # ๐๏ธ bobby
If you don't convert the variable to a string, you'll get a KeyError
exception.
my_dict = { '1': 'bobby', '2': 'hadz' } variable = 1 # โ๏ธ KeyError: print(my_dict[variable])
KeyError
exception is raised when we use square brackets to access a key that doesn't exist.You can use the same approach to access nested dictionaries using a variable as the key.
my_dict = { 'first_name': 'Bobby', 'last_name': 'Hadz', 'site': 'bobbyhadz.com', 'address': { 'country': 'Example' } } variable = 'site' print(my_dict[variable]) # ๐๏ธ bobbyhadz.com variable2 = 'address' variable3 = 'country' print(my_dict[variable2][variable3]) # ๐๏ธ Example
dict.get()
method insteadAlternatively, you can use the dict.get()
method.
my_dict = { '1': 'bobby', '2': 'hadz' } variable = 1 print(my_dict.get(str(variable))) # ๐๏ธ bobby # --------------------------------- my_dict = { 'first_name': 'Bobby', 'last_name': 'Hadz', 'site': 'bobbyhadz.com', 'address': { 'country': 'Example' } } variable = 'site' print(my_dict.get(variable)) # ๐๏ธ bobbyhadz.com
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', } variable = 'site' print(my_dict.get(variable)) # ๐๏ธ bobbyhadz.com variable2 = 'another' print(my_dict.get(variable2)) # ๐๏ธ None print(my_dict.get(variable2, 'default value')) # ๐๏ธ default value
In the last example, the specified key doesn't exist, so the provided default value is returned.
If you need to get a dictionary key as a variable:
for
loop to iterate over the dictionary's items.my_dict = { 'first_name': 'Bobby', 'last_name': 'Hadz', 'site': 'bobbyhadz.com' } # โ get dictionary keys and values as variables for key in my_dict: # first_name Bobby # last_name Hadz # site bobbyhadz.com print(key, my_dict[key]) for key, value in my_dict.items(): # first_name Bobby # last_name Hadz # site bobbyhadz.com print(key, value)
The first example uses a for loop to iterate directly over the dictionary.
The key
variable stores the key of the current iteration.
my_dict = { 'first_name': 'Bobby', 'last_name': 'Hadz', 'site': 'bobbyhadz.com' } for key in my_dict: # first_name Bobby # last_name Hadz # site bobbyhadz.com print(key, my_dict[key])
You can use square brackets if you need to access the corresponding value.
You can also use the dict.items()
method to get the dictionary's keys and
values as variables.
my_dict = { 'first_name': 'Bobby', 'last_name': 'Hadz', 'site': 'bobbyhadz.com' } for key, value in my_dict.items(): # first_name Bobby # last_name Hadz # site bobbyhadz.com print(key, value)
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, the key
variable stores the key of the current iteration
and the value
variable stores the corresponding value.
If you need to store a specific dictionary key in a variable, convert the dictionary to a list of keys and access the key at its index.
my_dict = { 'first_name': 'Bobby', 'last_name': 'Hadz', 'site': 'bobbyhadz.com' } first_key = list(my_dict)[0] print(first_key) # ๐๏ธ first_name first_value = list(my_dict.values())[0] print(first_value) # ๐๏ธ Bobby
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
.
We used the list() class to convert the dictionary to a list of keys.
my_dict = { 'first_name': 'Bobby', 'last_name': 'Hadz', 'site': 'bobbyhadz.com' } print(list(my_dict)) # ๐๏ธ ['first_name', 'last_name', 'site'] print(list(my_dict.keys())) # ๐๏ธ ['first_name', 'last_name', 'site']
We could have also used the dict.keys()
method to be more explicit.
The dict.keys() method returns a new view of the dictionary's keys.
If you need to store a specific dictionary value in a variable, convert the dictionary's values to a list and access the value at its index.
my_dict = { 'first_name': 'Bobby', 'last_name': 'Hadz', 'site': 'bobbyhadz.com' } first_value = list(my_dict.values())[0] print(first_value) # ๐๏ธ Bobby
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())
View objects are not subscriptable (cannot be accessed at an index), so we had to convert the view object to a list before accessing a specific value.
I've also written an article on how to assign a dictionary key or value to a variable.
You can learn more about the related topics by checking out the following tutorials: