Python dictionaries (dict
) are efficient ways of storing information. Just as an actual dictionary stores a word and its corresponding definition, so a Python dict
stores some key and a corresponding value. Using dictionaries can make your code more readable because a label is assigned to each value in the dictionary. Contrast this with list
objects, which are unlabeled. Dictionaries are created by using a set of curly brackets, {}
.
my_dict = {}
print(my_dict)
print(type(my_dict))
When we have a dict
, we can add values to it by using square brackets, []
. We put the key inside these square brackets. Usually, it is some string, but it can actually be any immutable type (e.g., a Python tuple
, which is the immutable form of a Python list
). Here we create two keys, fname
and lname
, for a first name and last name, respectively.
my_dict['fname'] = 'Daniel'
my_dict['lname'] = 'Chen'
We can also create a dictionary directly, with key–value pairs instead of adding them one at a time. To do this, we use our curly brackets, with the key–value pairs being specified by a colon.
my_dict = {'fname': 'Daniel', 'lname': 'Chen'}
print(my_dict)
To get the values from our keys, we can use the square brackets with the key inside.
fn = my_dict['fname']
print(fn)
We can also use the get
method.
ln = my_dict.get('lname')
print(ln)
The main difference between these two ways of getting the values from the dictionary is the behavior that occurs when you try to get a nonexistent key. When using the square brackets notation, trying to get a key that does not exist will return an error.
# will return an error
print(my_dict['age'])
In contrast, the get
method will return None
.
# will return None
print(my_dict.get('age'))
To get all the keys
from the dict
, we can use the keys
method.
# get all the keys in the dictionary
print(my_dict.keys())
To get all the values
from the dict
, we can use the values
method.
# get all the values in the dictionary
print(my_dict.values())
To get every key–value pair, you can use the items
method. This can be useful if you need to loop through a dictionary.
print(my_dict.items())
Each key–value pair is returned in a form of a tuple
, as indicated by the use of round brackets, ()
.
More on dictionaries can be found in the official documentation on data structures.1
1. https://docs.python.org/3/tutorial/datastructures.html#dictionaries
3.137.201.242