Python Dictionaries Documentation: How To Initialize And Work With Python Dictionaries?

How To Initialize And Work With Python Dictionaries

Python dictionaries are another useful built-in data type you should be competent in so you can manipulate complex data more efficiently. Here is what you should know about them, right from the very basics.

Python Dictionaries

In addition to sequences like lists and tuples, you can also store related data in dictionaries, another built-in complex data structure of Python.

While Python lists are usually called arrays in other programming languages, associative arrays or associative maps are similar abstract data types to Python dictionaries. Instead of using integer numbers of indexes, they are indexed by keys.

You can think of each element in a dictionary as a pair of a key and a corresponding value. Python organizes data in a dictionary through these associations. This mechanism is also how you can access elements of a dictionary. It is different from position-based structures like lists.

Dictionary Literals

The entire dictionary literal is enclosed by curly braces ({}), in which key-value pairs are written in sequence, separated by commas (,). In each pair, the key and the value are separated by a colon (:).

Keys can be of any immutable data type, not just integers, as long as it is unique in the dictionary. You can use numbers and strings for dictionary keys.

Even tuples are valid keys when they have only numbers, strings, or tuples. Lists can’t be used as keys because, unlike tuples, they aren’t immutable.

There are restrictions on the data types you can use for the associated values.

These are valid dictionary literals in Python:

{'name': 'LearnShareIT', 'url': 'learnshareit.com', 'categories': 10}
{1: 'Python', 2: 'JavaScript', 3: 'C++'}
{(1, 2): 'A', (2, 2): 'B'}
{}

In the first dictionary, we use strings as keys, while their associated values are strings or numbers. Meanwhile, the second dictionary has integers as its keys instead.

Remember that you can use tuples as keys, as we have shown in the third dictionary. If you don’t provide any pairs of keys and values, your literal represents an empty dictionary.

Create Dictionaries

You can simply use the assignment operator to create a dictionary from a literal and assign it to a variable:

>>> a = {1: 'Python', 2: 'JavaScript', 3: 'C++'}
>>> a
{1: 'Python', 2: 'JavaScript', 3: 'C++'}

It is important that position isn’t important in dictionaries. You shouldn’t rely on it, and Python only cares about the associations between keys and values.

The pair sequences in these dictionaries are different. But they are equal in Python because their key-value pairs are exactly the same:

>>> a = {1: 'A', 2: 'B'}
>>> b = {2: 'B', 1: 'A'}
>>> a == b
True

The dict() constructor provides another way to create dictionaries. As expected, it accepts literals, returning a new dictionary:

>>> a = dict({1: 'Python', 2: 'JavaScript', 3: 'C++'})
>>> a
{1: 'Python', 2: 'JavaScript', 3: 'C++'}

But you can also use iterable or mapping objects to create a dictionary with dict().

With literal objects like lists, all their elements must have exactly two objects. The dict() constructor will convert each element to a value pair, using the first object as the key and the second as the associated value.

This is an example demonstrating how to create a dictionary from a list with dict():

>>> list = [(1, 'Python'), (2, 'JavaScript'), (3, 'C++')]
>>> list
[(1, 'Python'), (2, 'JavaScript'), (3, 'C++')]
>>> dict(list)
{1: 'Python', 2: 'JavaScript', 3: 'C++'}

The same rule applies to mapping objects, such as ones created by map():

>>> a = [1, 2]
>>> b = ['Python', 'JavaScript']
>>> dict(zip(a, b))
{1: 'Python', 2: 'JavaScript'}

Working With Python Dictionaries

Access Values

You can use the key inside a pair of square brackets (the subscript operator) to access its associated value:

>>> a = {'name': 'John', 'age': 26}
>>> a['name']
'John'
>>> a['age']
26

The get() method is an alternative. When provided with a key that is in the dictionary, it returns the value for that key:

>>> a.get('name')
'John'
>>> a.get('age')
26

When the key you are looking for doesn’t exist in the dictionary, the subscript operator raises a KeyError, while get() returns None:

>>> a['gender']
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'gender'
>>> a.get('gender')

You can use the in keyword to check whether the dictionary has such a key:

>>> 'name' in a
True
>>> 'gender' in a
False

Add New Key-Value Pairs

Python dictionaries are mutable, meaning you can modify their contents directly.

To add a new key-value pair to an existing dictionary, simply assign the value with the key in a similar way to how you access that key:

>>> a['occupation'] = 'programmer'
>>> a
{'name': 'John', 'age': 26, 'occupation': 'programmer'}

Change Values Of Existing Keys

You can modify an existing value by using its associated key and assigning it to a new value:

>>> a['age'] = 30
>>> a
{'name': 'John', 'age': 30, 'occupation': 'programmer'}

Remove Entries

The pop() method removes a key from the dictionary (if it exists) while returns the value of the removed key:

>>> a
{'name': 'John', 'age': 26, 'occupation': 'programmer'}
>>> a.pop('occupation')
'programmer'
>>> a
{'name': 'John', 'age': 26}

The del statement works with dictionary entries as well:

>>> a
{'name': 'John', 'age': 26, 'occupation': 'programmer'}
>>> del a['occupation']
>>> a
{'name': 'John', 'age': 26}

The popitem() is useful when you want to remove key-value pairs in LIFO (last in, first out) order:

>>> a = {'name': 'John', 'age': 26, 'occupation': 'programmer'}
>>> a.popitem()
('occupation', 'programmer')
>>> a
{'name': 'John', 'age': 26}
>>> a.popitem()
('age', 26)

To remove every entry in a dictionary, use the clear() method:

>>> a.clear()
>>> a
{}

Loop Through A Dictionary

The for keyword can be used to iterate through all the keys of a dictionary:

>>> a = {'name': 'John', 'age': 26, 'occupation': 'programmer'}
>>> for i in a:
...     print(i)
... 
name
age
occupation

You can also do this with the keys() method, which returns a view object (of the class dict_keys) representing all the keys in the dictionary.

>>> for i in a.keys():
...     print(i)
... 
name
age
occupation

Dictionary Comprehension

Comprehension allows you to use math functions to create a new dictionary from an existing dictionary. This is an advanced transformation method that, when used properly, makes your code more elegant and concise, making it easier to understand and maintain.

In this example, the comprehension accesses every pair of key-value in the dictionary with the items() method. It builds a new dictionary by increasing the keys by 1 and lowering the letter case of their associated values:

>>> a = {0: 'ORANGE', 1: 'BLUE', 2: 'RED'}
>>> b = {key + 1: value.lower() for (key,value) in a.items()}
>>> b
{1: 'orange', 2: 'blue', 3: 'red'}

Tutorials

You can learn more about Dictionaries in Python in the articles below:

Summary Of Python Dictionaries

Python dictionaries are a built-in solution for storing data in associative keys and values. They don’t use positions to access or modify the entries., making dictionaries a good choice when you need to access data through keys instead.

Leave a Reply

Your email address will not be published. Required fields are marked *