Python create dictionary:

In Python, dictionaries are a built-in data type that allows you to store and retrieve key-value pairs. Dictionaries are defined using curly braces {} and consist of key-value pairs separated by colons.

Here’s a basic example:

my_dict = {‘key1’: ‘value1’, ‘key2’: ‘value2’, ‘key3’: ‘value3’}

Here are some common methods and operations you can perform with dictionaries:

1. Creating a Dictionary: 

In Python, you can create a dictionary using curly braces {} and specifying key-value pairs. Here’s a simple example:

# Creating a dictionary with three key-value pairs
my_dict = {‘key1’: ‘value1’, ‘key2’: ‘value2’, ‘key3’: ‘value3’}

# Printing the created dictionary
print(my_dict)

In this example, my_dict is a dictionary with three key-value pairs. The keys ('key1', 'key2', and 'key3') are strings, and the corresponding values ('value1', 'value2', and 'value3') can be of any data type (string, number, list, another dictionary, etc.).

You can also create an empty dictionary and add key-value pairs later:

# Creating an empty dictionary
empty_dict = {}

# Adding key-value pairs
empty_dict[‘name’] = ‘John’
empty_dict[‘age’] = 25

# Printing the modified dictionary
print(empty_dict)

In this example, empty_dict starts as an empty dictionary, and key-value pairs are added later using the square bracket notation.

Remember, keys in a dictionary must be unique, and they are typically immutable (strings, numbers, tuples). If you try to assign a value to an existing key, it will update the existing value associated with that key.

2. Accessing Values:

You can access values in a dictionary in Python using the keys associated with those values. Here’s how you can do it:

# Creating a dictionary
my_dict = {‘key1’: ‘value1’, ‘key2’: ‘value2’, ‘key3’: ‘value3’}

# Accessing values using keys
value1 = my_dict[‘key1’]
value2 = my_dict[‘key2’]
value3 = my_dict[‘key3’]

# Printing the values
print(value1) # Output: value1
print(value2) # Output: value2
print(value3) # Output: value3

In the example above, my_dict['key1'] accesses the value associated with 'key1', my_dict['key2'] accesses the value associated with 'key2', and so on.

It’s important to note that if you try to access a key that doesn’t exist in the dictionary, a KeyError will be raised. To avoid this, you can use the get() method, which allows you to provide a default value if the key is not present:

# Using get() to access values with a default value
value4 = my_dict.get(‘key4’, ‘default_value’)

# Printing the value
print(value4) # Output: default_value

In this case, since 'key4' is not present in the dictionary, the get() method returns the default value 'default_value'.

3. Adding or Updating Items:

In Python, you can add or update items in a dictionary by assigning values to specific keys. Here’s how you can do it:

  • Adding Items:

# Creating a dictionary
my_dict = {‘key1’: ‘value1’, ‘key2’: ‘value2’}

# Adding a new key-value pair
my_dict[‘new_key’] = ‘new_value’

# Printing the updated dictionary
print(my_dict)

In this example, a new key-value pair ('new_key', 'new_value') is added to the dictionary.

  • Updating Items:

# Updating the value of an existing key
my_dict[‘key1’] = ‘updated_value’

# Printing the updated dictionary
print(my_dict)

In this example, the value associated with 'key1' is updated to 'updated_value'.

If the specified key already exists in the dictionary, assigning a new value will update the existing value. If the key doesn’t exist, a new key-value pair will be created.

4. Removing Items:

In Python, you can remove items from a dictionary using various methods. Here are some common ways to remove items from a dictionary:

  • Using ‘del’ Statement: 

You can use the del statement to remove a specific key-value pair from a dictionary:

# Creating a dictionary
my_dict = {‘key1’: ‘value1’, ‘key2’: ‘value2’, ‘key3’: ‘value3’}

# Removing a specific key-value pair
del my_dict[‘key2’]

# Printing the updated dictionary
print(my_dict)

In this example, the key 'key2' and its corresponding value are removed from the dictionary.

  • Using ‘pop ()’ Method: 

The pop() method removes a specified key from the dictionary and returns its value:

# Creating a dictionary
my_dict = {‘key1′: ‘value1’, ‘key2’: ‘value2’, ‘key3’: ‘value3’}

# Removing and retrieving the value for a specific key
value = my_dict.pop(‘key1’)

# Printing the updated dictionary and the removed value
print(my_dict)
print(value)

  • Using ‘popitem ()’ Method: 

The popitem() method removes and returns an arbitrary key-value pair from the dictionary:

# Creating a dictionary
my_dict = {‘key1’: ‘value1’, ‘key2’: ‘value2’, ‘key3’: ‘value3’}

# Removing and retrieving an arbitrary key-value pair
key, value = my_dict.popitem()

# Printing the updated dictionary and the removed key-value pair
print(my_dict)
print(key, value)

In this example, an arbitrary key-value pair is removed from the dictionary, and the removed key and value are stored in the variables key and value, respectively.

  • Using ‘clear ()’ Method: 

The clear() method removes all items from the dictionary:

# Creating a dictionary
my_dict = {‘key1’: ‘value1’, ‘key2’: ‘value2’, ‘key3’: ‘value3‘}

# Removing all items from the dictionary
my_dict.clear()

# Printing the empty dictionary
print(my_dict)

In this example, all key-value pairs are removed from the dictionary, leaving it empty.

Choose the appropriate method based on whether you want to remove a specific key, an arbitrary key-value pair, or all items from the dictionary.

5. Checking for Key Existence:

In Python, you can check for the existence of a key in a dictionary using various methods. Here are common ways to check if a key exists in a dictionary:

  • Using the ‘in’ Operator: 

You can use the in operator to check if a key is present in the dictionary:

# Creating a dictionary
my_dict = {‘key1’: ‘value1’, ‘key2’: ‘value2’, ‘key3’: ‘value3’}

# Checking for key existence
if ‘key1’ in my_dict:
print(‘Key exists!’)
else:
print(‘Key does not exist.’)

In this example, the in operator is used to check if the key 'key1' exists in the dictionary my_dict.

  • Using the ‘get ()’ Method: 

The get() method allows you to retrieve the value for a given key and provides a default value if the key is not present:

# Creating a dictionary
my_dict = {‘key1’: ‘value1’, ‘key2’: ‘value2’, ‘key3’: ‘value3’}

# Checking for key existence using get()
value = my_dict.get(‘key1’, ‘default_value’)
if value != ‘default_value’:
print(‘Key exists!’)
else:
print(‘Key does not exist.’)

In this example, the get() method is used to check if the key 'key1' exists in the dictionary and retrieve its value. If the key is not present, the default value 'default_value' is returned.

  • Using Exception Handling (try and except):

You can use a try and except block to handle the case where a KeyError is raised when attempting to access a key that does not exist:

# Creating a dictionary
my_dict = {‘key1’: ‘value1’, ‘key2’: ‘value2’, ‘key3’: ‘value3’}

# Checking for key existence using try-except
try:
value = my_dict[‘key1’]
print(‘Key exists!’)
except KeyError:
print(‘Key does not exist.’)

In this example, the try block attempts to access the key 'key1', and if it exists, the message ‘Key exists!’ is printed. If a KeyError occurs (indicating that the key does not exist), the except block is executed, and the message ‘Key does not exist.’ is printed.

6. Getting Keys and Values:

In Python, you can retrieve the keys and values from a dictionary using various methods. Here are common ways to get keys and values:

  • Using keys() and value() Methods: 

# Creating a dictionary
my_dict = {‘key1’: ‘value1’, ‘key2’: ‘value2’, ‘key3’: ‘value3’}

# Getting keys
keys = my_dict.keys()

# Getting values
values = my_dict.values()

# Printing keys and values
print(“Keys:”, keys)
print(“Values:”, values)

The keys() method returns a view object that displays a list of all keys, and the values() method returns a view object that displays a list of all values.

  • Using item() Method: 

# Creating a dictionary
my_dict = {‘key1’: ‘value1’, ‘key2’: ‘value2’, ‘key3’: ‘value3’}

# Getting key-value pairs (items)
items = my_dict.items()

# Printing key-value pairs
print(“Key-Value Pairs:”, items)

The items() method returns a view object that displays a list of dictionary’s key-value tuple pairs.

  • Converting to Lists:

If you need the keys or values as actual lists, you can convert the views obtained from keys() and values() to lists:

# Creating a dictionary
my_dict = {‘key1’: ‘value1’, ‘key2’: ‘value2’, ‘key3’: ‘value3’}

# Getting keys as a list
keys_list = list(my_dict.keys())

# Getting values as a list
values_list = list(my_dict.values())

# Printing lists of keys and values
print(“Keys as List:”, keys_list)
print(“Values as List:”, values_list)

7. Iterating Over Keys or Items:

In Python, you can iterate over the keys, values, or key-value pairs (items) of a dictionary using various methods. Here are examples of iterating over keys and items:

  • Iterating Over Keys:

# Creating a dictionary

my_dict = {‘key1’: ‘value1’, ‘key2’: ‘value2’, ‘key3’: ‘value3’}

# Iterating over keys
for key in my_dict:
print(key)

This will output:

key1
key2
key3

  • Iterating Over Values:

# Creating a dictionary
my_dict = {‘key1’: ‘value1’, ‘key2’: ‘value2’, ‘key3’: ‘value3’}

# Iterating over values
for value in my_dict.values():
print(value)

This will output:

value1
value2
value3

  • Iterating Over Key-Value Pairs (Items):

# Creating a dictionary
my_dict = {‘key1’: ‘value1’, ‘key2’: ‘value2’, ‘key3’: ‘value3’}

# Iterating over key-value pairs (items)
for key, value in my_dict.items():
print(f”{key}: {value}”)

This will output:

key1: value1
key2: value2
key3: value3

These examples demonstrate how to use the for loop to iterate over the keys, values, or items of a dictionary. Depending on your specific use case, you can choose the type of iteration that suits your needs.

8. Copying a Dictionary:

In Python, there are a few ways to copy a dictionary. However, it’s important to note that not all methods create a completely independent copy. Here are two common ways to copy a dictionary:

  • Using copy() Method:

# Creating a dictionary
original_dict = {‘key1’: ‘value1’, ‘key2’: ‘value2’, ‘key3’: ‘value3’}

# Using copy() method
copied_dict = original_dict.copy()

# Modifying the copied dictionary
copied_dict[‘key1’] = ‘updated_value’

# Printing original and copied dictionaries
print(“Original Dictionary:”, original_dict)
print(“Copied Dictionary:”, copied_dict

The copy() method creates a shallow copy of the dictionary, meaning that it creates a new dictionary, but the elements (objects) within the dictionary are still references to the same objects as the original dictionary.

  • Using ‘dict()’ Constructor:

     

    # Creating a dictionary
    original_dict = {‘key1’: ‘value1’, ‘key2’: ‘value2’, ‘key3’: ‘value3’}

    # Using dict() constructor
    copied_dict = dict(original_dict)

    # Modifying the copied dictionary
    copied_dict[‘key1’] = ‘updated_value’

    # Printing original and copied dictionaries
    print(“Original Dictionary:”, original_dict)
    print(“Copied Dictionary:”, copied_dict)

    Similar to the copy() method, using the dict() constructor creates a shallow copy of the dictionary.

  • Creating a Deep Copy using ‘copy()’ Module:

If your dictionary contains nested structures or other mutable objects, and you want to create a completely independent copy, you can use the copy module to create a deep copy:

import copy

# Creating a dictionary with nested structure
original_dict = {‘key1’: ‘value1’, ‘nested_dict’: {‘key2’: ‘value2’}}

# Using copy.deepcopy() for deep copy
deep_copied_dict = copy.deepcopy(original_dict)

# Modifying the deep copied dictionary
deep_copied_dict[‘nested_dict’][‘key2‘] = ‘updated_value’

# Printing original and deep copied dictionaries
print(“Original Dictionary:”, original_dict)
print(“Deep Copied Dictionary:”, deep_copied_dict)

The deepcopy() function from the copy module creates a new dictionary with copies of all nested objects, ensuring complete independence.

Choose the method that best fits your requirements based on the structure of your dictionary and whether you need a shallow or deep copy.

9. Merging Dictionaries:

In Python, you can merge dictionaries using the update() method or the {**d1, **d2} syntax. Here are examples of both methods:

  • Using ‘update()’ Method:

# Creating two dictionaries
dict1 = {‘key1’: ‘value1’, ‘key2’: ‘value2’}
dict2 = {‘key3’: ‘value3’, ‘key4’: ‘value4’}

# Merging dictionaries using update()
dict1.update(dict2)

# Printing the merged dictionary (dict1 is modified in-place)
print(“Merged Dictionary:”, dict1)

In this example, the update() method is used to merge dict2 into dict1. If there are common keys, the values from dict2 will overwrite the values in dict1 for those keys.

  • Using {**d1, **d2} Syntax (Python 3.5 and later):

# Creating two dictionaries
dict1 = {‘key1’: ‘value1’, ‘key2’: ‘value2’}
dict2 = {‘key3’: ‘value3’, ‘key4’: ‘value4’}

# Merging dictionaries using the {**d1, **d2} syntax
merged_dict = {**dict1, **dict2}

# Printing the merged dictionary (new dictionary is created)
print(“Merged Dictionary:”, merged_dict)

In this example, the {**d1, **d2} syntax creates a new dictionary that is a merge of dict1 and dict2. This method does not modify the original dictionaries.

Choose the method that best fits your requirements. If you want to modify one of the dictionaries in-place, use the update() method. If you want to create a new merged dictionary without modifying the originals, use the {**d1, **d2} syntax.

10. Sorting:

In Python, dictionaries are inherently unordered. Starting from Python 3.7, the insertion order of items in a dictionary is preserved, but it’s important to note that dictionaries themselves do not have a specific order. If you need to sort a dictionary by keys or values, you can achieve this using the sorted() function or the items() method.

  • Sorting by Keys:

# Creating an unordered dictionary
my_dict = {‘banana’: 3, ‘apple’: 1, ‘orange’: 2}

# Sorting dictionary by keys
sorted_dict_by_keys = dict(sorted(my_dict.items()))

# Printing the sorted dictionary by keys
print(sorted_dict_by_keys)

This will output a dictionary with keys sorted alphabetically:

{‘apple’: 1, ‘banana’: 3, ‘orange‘: 2}

  • Sorting by Values:

# Creating an unordered dictionary
my_dict = {‘banana’: 3, ‘apple’: 1, ‘orange’: 2}

# Sorting dictionary by values
sorted_dict_by_values = dict(sorted(my_dict.items(), key=lambda item: item[1]))

# Printing the sorted dictionary by values
print(sorted_dict_by_values)

This will output a dictionary with values sorted in ascending order:

{‘apple’: 1, ‘orange’: 2, ‘banana’: 3}

In this example, the key parameter of the sorted() function is used to specify a lambda function that returns the second element of each key-value pair (i.e., the values). Adjust the key parameter if you want to sort by a different criterion.

Remember that the result is a new dictionary, and dictionaries themselves do not guarantee order. If you need an ordered dictionary, you can use the collections.OrderedDict class, which maintains the order of items based on their insertion order.

11. Nested Dictionaries:

In Python, you can create nested dictionaries, which are dictionaries within dictionaries. This allows you to organize data in a hierarchical structure. Here’s an example of creating and working with nested dictionaries:

# Creating a nested dictionary
employee_data = {
‘John Doe’: {
‘age’: 30,
‘position’: ‘Software Engineer’,
‘skills’: [‘Python’, ‘JavaScript’, ‘SQL’]
},
‘Alice Smith’: {
‘age’: 28,
‘position’: ‘Data Scientist’,
‘skills’: [‘R’, ‘Python’, ‘Machine Learning’]
},
‘Bob Johnson’: {
‘age’: 35,
‘position’: ‘Project Manager’,
‘skills’: [‘Project Management’, ‘Communication’]
}
}

# Accessing data in the nested dictionary
john_age = employee_data[‘John Doe’][‘age’]
alice_skills = employee_data[‘Alice Smith’][‘skills’][0]

# Modifying data in the nested dictionary
employee_data[‘Bob Johnson’][‘position’] = ‘Senior Project Manager’
employee_data[‘Alice Smith’][‘skills’].append(‘Deep Learning’)

# Printing the modified nested dictionary
print(employee_data)

In this example, employee_data is a nested dictionary where each employee’s data is represented as a dictionary within the main dictionary. You can access individual values using multiple keys.

Output:

{
‘John Doe’: {
‘age’: 30,
‘position’: ‘Software Engineer’,
‘skills’: [‘Python’, ‘JavaScript’, ‘SQL’]
},
‘Alice Smith’: {
‘age’: 28,
‘position’: ‘Data Scientist’,
‘skills’: [‘R’, ‘Python’, ‘Machine Learning’, ‘Deep Learning’]
},
‘Bob Johnson’: {
‘age’: 35,
‘position’: ‘Senior Project Manager’,
‘skills’: [‘Project Management’, ‘Communication’]
}
}

Nested dictionaries are useful for representing structured data, such as organizational hierarchies, configuration settings, or any other data that naturally forms a hierarchy

Scroll to Top