Dictionaries

Dictionaries

A dictionary is a collection of unordered, modifiable(mutable) paired (key: value) data type.

Creating a Dictionary

To create a dictionary we use curly brackets, {} or the dict() built-in function.

Example:

The dictionary above shows that a value could be any data types:string, boolean, list, tuple, set or a dictionary.

Dictionary Length

It checks the number of 'key: value' pairs in the dictionary.

Example:

Accessing Dictionary Items

We can access Dictionary items by referring to its key name.

Example:

Accessing an item by key name raises an error if the key does not exist. To avoid this error first we have to check if a key exist or we can use the get method. The get method returns None, which is a NoneType object data type, if the key does not exist.

Adding Items to a Dictionary

We can add new key and value pairs to a dictionary

Example:

Modifying Items in a Dictionary

We can modify items in a dictionary

Example:

Checking Keys in a Dictionary

We use the in operator to check if a key exist in a dictionary

Removing Key and Value Pairs from a Dictionary

  • pop(key): removes the item with the specified key name:

  • popitem(): removes the last item

  • del: removes an item with specified key name

Example:

Changing Dictionary to a List of Items

The items() method changes dictionary to a list of tuples.

Clearing a Dictionary

If we don't want the items in a dictionary we can clear them using clear() method

Deleting a Dictionary

If we do not use the dictionary we can delete it completely

Copy a Dictionary

We can copy a dictionary using a copy() method. Using copy we can avoid mutation of the original dictionary.

Getting Dictionary Keys as a List

The keys() method gives us all the keys of a a dictionary as a list.

Getting Dictionary Values as a List

The values method gives us all the values of a a dictionary as a list.

Last updated

Was this helpful?