Python Dictionaries Tutorial

Python dictionaries are something completely different, they are not sequences at all, but are rather known as mappings. In this article, I will introduce you to a tutorial on Python dictionaries.

Python Dictionaries

Mappings are collections of other objects, but they store objects by key rather than relative position. Mappings do not maintain any reliable left-to-right order; they just map the keys to the associated values. Dictionaries, the only type of mapping of Python’s core set of objects, are also editable like lists, they can be edited in place, and can grow and shrink on demand.

Like lists, they are a flexible tool for representing collections, but their more mnemonic keys are best suited when items in a collection are named or tagged like fields in a database record, for example.

When written as literals, dictionaries are encoded in curly braces and consist of a series of “key: value” pairs. Dictionaries are useful whenever we need to associate a set of values with keys to describe the properties of something, for example. As an example, consider the following three-element dictionary:

D = {'food': 'Spam', 'quantity': 4, 'color': 'pink'}
D
{'color': 'pink', 'food': 'Spam', 'quantity': 4}

We can index this dictionary by key to retrieve and modify the values associated with the keys. The dictionary indexing operation uses the same syntax as that used for sequences, but the element in square brackets is a key, not a relative position:

D['food']
'Spam'
D['quantity'] += 1
D
{'color': 'pink', 'food': 'Spam', 'quantity': 6}

Although the literal form of braces is used, it is perhaps more common to see dictionaries created in different ways. The following code, for example, starts with an empty dictionary and fills it one key at a time. Unlike out-of-range assignments in lists, which are prohibited, assignments to new dictionary keys create these keys:

D = {}
D['name'] = 'Bob'
D['job'] = 'dev'
D['age'] = 40
D
{'age': 40, 'job': 'dev', 'name': 'Bob'}

Here we are effectively using dictionary keys as field names in a record that describes someone. In other applications, dictionaries can also be used to replace search operations, indexing a dictionary by key is often the fastest way to code a search in Python.

I hope you liked this article on a tutorial on Python Dictionaries. Feel free to ask your valuable questions in the comments section below.

Aman Kharwal
Aman Kharwal

I'm a writer and data scientist on a mission to educate others about the incredible power of data📈.

Articles: 1433

Leave a Reply