Subscribe to my email list now at http://jauyeung.net/subscribe/
Follow me on Twitter at https://twitter.com/AuMayeung
Many more articles at https://medium.com/@hohanga
Even more articles at http://thewebdev.info/
Python is a convenient language that’s often used for scripting, data science, and web development.
In this article, we’ll look at how to define and use Python dictionaries to store key-value pairs.
The Dictionary Data Type
A dictionary is a data structure that stores a collection of key-value pairs.
The keys can of any data type.
Dictionaries are denoted with braces and the key-value pairs inside it.
For instance, we can define one as follows:
person = {'first_name': 'Jane', 'last_name': 'Smith' }
In the code above, 'first_name'
and 'last_name'
are keys, and 'Jane'
and 'Smith'
are the respective values of those keys.
We can access the value given the key by writing:
person['first_name']
Then ‘Jane’
is returned.
The order of the keys doesn’t matter, so given:
jane_1 = {'first_name': 'Jane', 'last_name': 'Smith' }
jane_2 = {'last_name': 'Smith', 'first_name': 'Jane' }
Then:
jane_1 == jane_2
returns True
.
Ordered Dictionaries in Python 3.7
Since Python 3.7, when we convert a dictionary to a list of keys, the insertion order will be preserved.
For instance, if we have:
jane_1 = {'first_name': 'Jane', 'last_name': 'Smith' }
jane_2 = {'last_name': 'Smith', 'first_name': 'Jane' }
Then:
list(jane_1)
returns:
['first_name', 'last_name']
And:
list(jane_2)
returns:
['last_name', 'first_name']
The keys(), values(), and items() Methods
We can use the keys
method to get the keys of a dictionary.
For instance, if we have:
person = {'first_name': 'Jane', 'last_name': 'Smith' }
Then person.keys()
returns:
dict_keys(['first_name', 'last_name'])
We can loop through the keys as follows:
for k in person.keys():
print(k)
Then we get:
first_name
last_name
displayed on the screen.
Likewise, we can do the same thing with the values
method to return the values of a dictionary.
person.values()
returns:
dict_values(['Jane', 'Smith'])
We loop through the values as follows:
for v in person.values():
print(v)
Then we get:
Jane
Smith
on the screen.
The items
method returns both the keys and values of each entry.
For instance, we person.items()
returns:
dict_items([('first_name', 'Jane'), ('last_name', 'Smith')])
We can loop through the keys and values together as follows:
for k, v in person.items():
print('%s: %s' % (k, v))
Then we get:
first_name: Jane
last_name: Smith
displayed on the screen.
Checking Whether a Key or Value Exists in a Dictionary
We can check if a key is in a dictionary with the in
operator. For instance, given that we have:
person = {'first_name': 'Jane', 'last_name': 'Smith' }
Then:
'first_name' in person.keys()
returns True
.
The get() Method
The get
method returns the value for the given key. It takes the key as the first argument and the default value as the second argument.
For instance, given the following dictionary:
store = { 'apples': 5, 'oranges': 10, 'grapes': 12}
store.get(‘pear’, 0)
returns 0 since we have 0 as the default value passed in as the 2nd argument and 'pear'
isn’t a key in store
.
If we have store.get(‘pear’)
, then get
returns None
since we didn’t specify a return value.
On the other hand, if we have store.get(‘apples’)
, we get 5 returned from the store
dictionary.
The setdefault() Method
We can call setdefault
to set the default value of a given key if it doesn’t exist in the dictionary.
For example, if we have:
store = { 'apples': 5, 'oranges': 10, 'grapes': 12}
store.setdefault('pears', 5)
Then store[‘pears’]
returns 5 according to the value that we set by setdefault
.
Pretty Printing
We can print a dictionary on the screen in an easy to read fashion by using the pprint
module.
For instance:
import pprint
store = { 'apples': 5, 'oranges': 10, 'grapes': 12}
pprint.pprint(store)
displays:
{'apples': 5, 'grapes': 12, 'oranges': 10}
on the screen.
Conclusion
We can use dictionaries to store key-value pairs and get values by its keys.
Also, we can iterate through the keys, values, or both together with the keys()
, values()
, and items()
methods respectively.
Top comments (0)