Dictionaries

Dictionaries in Python are special data types(known as mapping types) in Python where data is stored as key-value pairs(values are mapped to keys). Unlike lists, dictionaries cannot be indexed by numbers. Rather, they are indexed using keys. Key-value pairs in dictionaries are separated by commas and enclosed within curly braces({}). 

Creating a dictionary

We can create an empty dictionary as follows:

A dictionary with key-value pairs can be created as follows:

person = { “firstname”: “Charles”, “lastname”: “Babbage” }

Accessing values inside dictionaries

The values inside the dictionary can be accessed using the keys as follows:

Here, we are using the keys inside square brackets just like what we did for lists. The only difference is that lists use numbered index whereas dictionaries use keyed index.

Please note that we can access values using only existing keys. Accessing using a non-existing key will throw an error.

Output:

KeyError: ‘fullname’

Adding new values to dictionaries

We can add more values to the dictionary using new keys.

Output:

{‘firstname’: ‘Charles’, ‘lastname’: ‘Babbage’, ‘age’: 50}

Please note that we are using a new(non-existing) key to add a new value. If we use an existing key, the old value will be replaced by the new one.

Output:

{‘firstname’: ‘Charles’, ‘lastname’: ‘Darwin’}

Deleting existing key-value pairs

We can delete an existing key-value pair using the del keyword.

Output:

{‘firstname’: ‘Charles’}

Here, we have to use an existing key in the del statement. Otherwise, we get an error.