The dictionary is one of Python’s most powerful data types. In other programming languages and computer science in general, dictionaries are also known as associative arrays. They allow you to associate one or more keys to values.
In this article, we share some beyond the basics tips and tricks. You can read our tutorial on Python dictionaries for a complete overview of the basics.
Table of Contents
Valid dictionary keys
You can put anything in a dictionary. You’re not limited to numbers or strings. In fact, you can put dictionaries and Python lists inside your dictionary and access the nested values in a very natural way.
If you want, you can go pretty crazy on your dictionary keys too. The only requirement is that the key is hashable. Mutable types like lists, dictionaries, and sets won’t work and result in an error like: TypeError: unhashable type: ‘dict’
.
Besides this limitation, you can use all data types as a dictionary key, including native types like float
and int
or even a class name or object. Although completely useless for most, I’ll demonstrate anyway:
>>> crazy_dictionary = { int: 1, float: 2, dict: 3 } >>> crazy_dictionary[dict] 3 >>> class P: ... pass ... >>> crazy_dictionary[P]=1 >>> p = P() >>> crazy_dictionary[p]=2
A more likely use case is the use of numbers as keys. For example, consider this registration of runners in a marathon:
>>> runners = { 1000: 'Jack', 1001: 'Eric', 1002: 'Lisa' } >>> runners[1001] 'Eric'
Multiple ways to create a dictionary
There are more advanced ways to initialize a dictionary that might come in handy, depending on your data source.
Using the dict() constructor
The dict()
function builds a dictionary from a sequence or list of key-value pairs:
>>> dict([ ('Jack', '070-02222748'), ('Pete', '010-2488634'), ('Eric', '06-10101010') ]) {'Jack': '070-02222748', 'Pete': '010-2488634', 'Eric': '06-10101010'}
Dictionary Comprehensions
Analogous to list comprehensions, you can also use dictionary comprehensions to create a new dictionary:
>>> {x: x**2 for x in (2, 4, 6)} {2: 4, 4: 16, 6: 36}
Please read our article on list comprehensions for a more detailed explanation.
Using dict.fromkeys
The dict.fromkeys(keys, value)
method creates a new dictionary, based on the list of keys
supplied to it. The value of all elements will be set to the supplied value
, or None
by default, if you don’t supply a value.
See the following code:
>>> names = ('Eric', 'Martha', 'Ellen') >>> phone_numbers = dict.fromkeys(names, None) >>> phone_numbers {'Ellen': None, 'Eric': None, 'Martha': None}
Parse a JSON Object
As explained in my article on working with JSON, you can also decode JSON data into a dictionary like this:
>>> import json >>> jsonstring = '{ "name": "erik", "age": 38, "married": true}' >>> json.loads(jsonstring) {'name': 'erik', 'age': 38, 'married': True}
Default values and dict.get()
The get-method is a convenient way to retrieve a single value from a dictionary. The advantage? It returns a default value, None, if the key is not found. You can specify your own default value too.
With the get-method, you don’t have to surround the operation with a try… except. It’s ideal when working with configuration data that is parsed from YAML or JSON files, where your software offers defaults for unset configuration items.
An example:
>>> config = { 'host': 'example.org' } >>> config.get('port', 80) 80 >>> config.get('schema') None
Dictionary view objects
Some built-in dictionary methods return a view object, offering a window on your dictionary’s keys and values. Before we start using such view objects, there’s an important concept you need to understand: values in a view object change as the content of the dictionary changes.
Values in a view object change as the content of the dictionary changes.
dict.keys() and dict.values()
This is best illustrated with an example, in which we use two of these views: keys() and values(). Keys returns a view on all the keys of a dictionary, while values() returns a view on all its values:
phone_numbers = { 'Jack': '070-02222748', 'Pete': '010-2488634', 'Eric': '06-10101010' } names = phone_numbers.keys() numbers = phone_numbers.values() phone_numbers['Linda'] = '030-987612312' print(names) print(numbers) # Loop through a view object with: for number in numbers: print(number)
dict.items(): loop through a Python dictionary
The items()
method of a dictionary returns an iterable view object, offering both the keys and values, as can be seen below. You can loop through this object with a simple Python for-loop:
>>> phone_numbers.items() dict_items([('Jack', '070-02222748'), ('Pete', '010-2488634'), ('Eric', '06-10101010')]) >>> for name, phonenr in phone_numbers.items(): ... print(name, ":", phonenr) ... Jack : 070-02222748 Pete : 010-2488634 Eric : 06-10101010
I hope you learned something new! Let me know in the comments, and perhaps you have more tips or tricks to share regarding dictionaries.