Python Dictionary

A Python dictionary is a built-in data structure that stores key-value pairs, where each key is unique and used to retrieve its associated value. It is unordered, mutable, and can be indexed, sliced, and manipulated with a set of built-in methods. Dictionaries are defined using curly braces {} and colons to separate keys from values. A simple example demonstrating the basic usage of a Python dictionary:
# Create a Python dictionary person = {'name': 'John Doe', 'age': 30, 'country': 'USA'}
# Access Dictionary values by key print("Name: ", person['name']) print("Age: ", person['age']) print("Country: ", person['country'])
# Update a Dictionary value by key person['age'] = 35 print("Updated Age: ", person['age'])
# Add a new key-value pair person['gender'] = 'Male' print("Gender: ", person['gender'])
# Remove a key-value pair del person['gender'] print("Dictionary after removing gender: ", person)
# Check if a key is in the dictionary if 'name' in person: print("Name key is present in the dictionary.") else: print("Name key is not present in the dictionary.")
//Output: Name: John Doe Age: 30 Country: USA Updated Age: 35 Gender: Male Dictionary after removing gender: {'name': 'John Doe', 'age': 35, 'country': 'USA'} Name key is present in the dictionary.

Data type of the keys and values

Dictionaries can have keys and values of different data types. The data type of the keys and values in a dictionary can be anything, including integers, strings, lists, or even other dictionaries. The only requirement for the keys is that they must be hashable, meaning they can be converted to a hash value, which can be used to quickly search for the keys in the dictionary. Examples of hashable data types include strings, numbers, and tuples, while examples of unhashable data types include lists and dictionaries.

Not allowed Duplicates

Dictionaries in Python do not allow duplicate values. The keys in a dictionary are unique, and adding a new key-value pair with a key that already exists in the dictionary will overwrite the previous value associated with that key.

Create a dictionary in Python

You can create a dictionary in Python by enclosing a comma-separated list of key-value pairs within curly braces {}.

String keys and integer values

# Create a dictionary with string keys and integer values my_dict = {'one': 1, 'two': 2, 'three': 3}

Mixed keys and values

# Create a dictionary with mixed keys and values mixed_dict = {1: 'one', 'two': 2, 3.14: [1, 2, 3]}

Empty dictionary

# Create an empty dictionary empty_dict = {}

Using dict() constructor

You can also create a dictionary using the dict() constructor:

# Create a dictionary using the dict() constructor my_dict = dict(one=1, two=2, three=3)

Add Elements to a Python Dictionary

You can add elements to a Python dictionary by assigning values to new keys or by modifying existing keys.

Here is an example of adding new key-value pairs to a dictionary:

my_dict = {} # Create an empty dictionary # Add new key-value pairs to the dictionary my_dict['one'] = 1 my_dict['two'] = 2 my_dict['three'] = 3 print(my_dict)
//Output: {'one': 1, 'two': 2, 'three': 3}

Update the values of python Dictionary

Here is an example of modifying existing key-value pairs in a dictionary:
my_dict = {'one': 1, 'two': 2, 'three': 3} my_dict['two'] = 22 # Modify an existing key-value pair print(my_dict)
//Output: {'one': 1, 'two': 22, 'three': 3}
If the key you are trying to update does not already exist in the dictionary, it will be added to the dictionary with the specified value:
my_dict = {'one': 1, 'two': 2, 'three': 3} # Create a dictionary my_dict['four'] = 4 # Update the value of a non-existent key print(my_dict)
//Output: {'one': 1, 'two': 2, 'three': 3, 'four': 4}

Accessing Elements from Python Dictionary

You can access the value of a specific key in a Python dictionary by using square bracket notation and the key as an index:
my_dict = {'one': 1, 'two': 2, 'three': 3} # Create a dictionary value = my_dict['two'] # Access the value of a specific key print(value) #//Output: 2


If you try to access a key that does not exist in the dictionary, a KeyError will be raised:
my_dict = {'one': 1, 'two': 2, 'three': 3} # Create a dictionary # Try to access a key that does not exist in the dictionary value = my_dict['four']
//Output: KeyError: 'four'

get() method

To avoid raising a KeyError, you can use the get() method, which will return None if the key is not found:
my_dict = {'one': 1, 'two': 2, 'three': 3} # Create a dictionary value = my_dict.get('four') print(value) #//Output: None

Removing elements from python Dictionary

You can remove elements from a Python dictionary using the del statement or the pop() method.

del statement

Here is an example of using the del statement:
my_dict = {'one': 1, 'two': 2, 'three': 3} # Create a dictionary del my_dict['two'] print(my_dict)
//Output: {'one': 1, 'three': 3}

pop() method

Example of using the pop() method:
my_dict = {'one': 1, 'two': 2, 'three': 3} # Create a dictionary value = my_dict.pop('two') print(value) #//Output: 2 print(my_dict) #//Output: {'one': 1, 'three': 3}

Advantages of python dictionary

how to use Python dictionary
  1. Fast look-up: Dictionaries provide an efficient and fast way of looking up values based on their keys, as they use hash tables to store the key-value pairs.
  2. Mutable: Dictionaries are mutable, which means you can change the values stored in them by adding, removing, or modifying the key-value pairs.
  3. Flexible data types: Dictionaries can store values of any data type, including other dictionaries, making them very versatile.
  4. Easy to use: Dictionaries are easy to use, as they allow you to store and retrieve values based on keys, which can be any immutable type. This makes it easy to work with large amounts of data.
  5. Dynamic: Dictionaries are dynamic, meaning their size can change as you add or remove key-value pairs. This makes them an ideal choice for working with data that may change during the course of a program.

Python Dictionary Methods (Summary):

Here are some important methods that can be used with Python dictionaries:
  1. clear(): Removes all items from the dictionary.
  2. copy(): Returns a shallow copy of the dictionary.
  3. fromkeys(seq[, value]): Creates a new dictionary with keys from seq and values set to value.
  4. get(key[, default]): Returns the value of key. If key is not in the dictionary, it returns default (which is None by default).
  5. items(): Returns a view of the dictionary's key-value pairs as a list of tuples.
  6. keys(): Returns a view of the dictionary's keys as a list.
  7. pop(key[, default]): Removes the specified key from the dictionary and returns its value. If the key is not found, it returns default (which is None by default).
  8. setdefault(key[, default]): If key is in the dictionary, returns its value. If key is not in the dictionary, inserts key with a value of default (which is None by default) and returns default.
  9. popitem(): Removes and returns an arbitrary (key, value) pair from the dictionary.
  10. update([other]): Adds the key-value pairs from other to the dictionary. If a key already exists in the dictionary, its value will be updated.
  11. values(): Returns a view of the dictionary's values as a list.