Python Dictionary Tutorial with Examples

Python Dictionaries

A Python Dictionary represents one of the fundamental data types available for storing data in 'key: value' pairs. This collection is characterized as unordered, mutable, and indexed, where each key is distinct and corresponds to a specific value. Dictionaries are frequently utilized for holding related information, such as data linked to a specific entity or object, allowing for straightforward retrieval of a value based on its associated key.

Let us examine a basic instance of a dictionary.

Example

Example

# creating a Dictionary

D = {1: 'Learn', 2: 'Python', 3: 'from', 4: 'Example', 5: 'Tech'}

print(D)

Output:

Output

{1: 'Learn', 2: 'Python', 3: 'from', 4: 'Example', 5: 'Tech'}

Explanation:

In the preceding illustration, we have constructed a basic dictionary that contains several 'key: value' pairs.

In Python, a dictionary serves as a mapping data structure that links one object to another. To create this association between a key and its corresponding value, we utilize the colon ':' symbol to separate the two.

Characteristics of Python Dictionary

A dictionary in Python is a data type with the following characteristics:

  • Mutable: Dictionaries can be modified after initialization allowing us to add, remove or update 'key: value' pairs.
  • Unordered: Python dictionary does not follow a particular order to store items. However, starting from Python 3.7 , the feature for the dictionary to maintain the insertion order of the items was added.
  • Indexed: Unlike lists or tuples , which are indexed by position, dictionaries use keys to access values, offering faster and more readable data retrieval.
  • Unique Keys: Each key in a dictionary must be unique. If we try to assign a value to an existing key, the old value will be replaced by the new one.
  • Heterogeneous: Keys and values in a dictionary can be of any type.
  • Creating a Dictionary

In Python, a dictionary can be formed by placing a collection of 'key: value' pairs within curly braces, with each pair separated by commas. Alternatively, we have the option to utilize Python's built-in dict function to achieve the same result.

Python Example to Create a Dictionary

Below is a straightforward illustration demonstrating two methods for constructing a dictionary in Python.

Example

Example

# simple example to create python dictionary

# creating dictionaries

dict_zero = {}     # empty dictionary

dict_one = {"name": "Lucy", "age": 19, "city": "New Jersey"} # using {}

dict_two = dict(name = "Yshakan", age = 21, city = "Havana")  # using dict()

# printing the results

print("Empty Dictionary:", dict_zero)

print("Dictionary 1 (created using {}):", dict_one)

print("Dictionary 2 (created using dict()):", dict_two)

Output:

Output

Empty Dictionary: {}

Dictionary 1 (created using {}): {'name': 'Lucy', 'age': 19, 'city': 'New Jersey'}

Dictionary 2 (created using dict()): {'name': 'John', 'age': 21, 'city': 'Havana'}

Explanation:

The preceding example illustrates various methods for constructing dictionaries in Python. Additionally, we have explored the process of initializing an empty dictionary.

Note: The dict function can also be used to transform an existing data type into a dictionary.

Accessing Dictionary Items

In Python, we can retrieve the value associated with a specific key in a dictionary by enclosing the key within square brackets ''. Alternatively, we can utilize the get method to access items in the dictionary.

Python Example to Access a Dictionary

Below is a straightforward illustration demonstrating the various methods for retrieving items from a dictionary in Python.

Example

Example

# simple example to access dictionary items

# given dictionary

dict_x = {

    "name": "Sachin",

    "age": 18,

    "gender": "male",

    "profession": "student"

    }

print("Person's Details")

# accessing dictionary items using keys

print("Name:", dict_x["name"])

print("Age:", dict_x["age"])

# accessing dictionary items using get()

print("Gender:", dict_x.get("gender"))

print("Profession:", dict_x.get("profession"))

Output:

Output

Person's Details

Name: Sachin

Age: 18

Gender: male

Profession: student

Explanation:

In this section, we have retrieved the various values associated with the items in the dictionary by utilizing both the square brackets notation and the get function.

Adding Items to a Dictionary

The dictionary is a mutable data structure that enables the addition of new items. This operation can be performed by associating a value with a new key.

Python Example to Add Items to a Dictionary

Let us examine a straightforward illustration demonstrating the process of incorporating items into a Python dictionary.

Example

Example

# simple example to add item to dictionary

# given dictionary

dict_x = {

    "name": "Sachin",

    "age": 18,

    "gender": "male",

    "profession": "student"

    }

print("Given Dictionary:", dict_x)

# adding an item to the dictionary

dict_x["country"] = "India"

print("Updated Dictionary:", dict_x)

Output:

Output

Given Dictionary: {'name': 'Sachin', 'age': 18, 'gender': 'male', 'profession': 'student'}

Updated Dictionary: {'name': 'Sachin', 'age': 18, 'gender': 'male', 'profession': 'student', 'country': 'India'}

Explanation:

In this illustration, we have introduced a new 'key: value' pair into the dictionary by utilizing the assignment operator.

Removing Items from a Dictionary

Python offers multiple ways to remove items from a given dictionary, such as:

  • del : This keyword is used to remove an item by key.
  • pop : This method is used to remove an item by key. It also returns the value of the removed item.
  • popitem: This method removes and returns the last 'key: value' pair.
  • clear: This method is used to remove all items from the dictionary.
  • Python Example to Remove Items from a Dictionary Using Different Methods

Below is an illustration demonstrating various techniques to eliminate entries from a Python dictionary.

Example

Example

# simple example to remove items from a dictionary

# given dictionary

dict_x = {

    "name": "Sachin",

    "age": 18,

    "gender": "male",

    "profession": "student",

    "country": "India"

    }

print("Given Dictionary:", dict_x)

# removing items from the dictionary

del dict_x['age']     # using del

print("Updated Dictionary (Removed 'age'):", dict_x)

popped_value = dict_x.pop('gender')  # using pop()

print("Updated Dictionary (Removed 'gender'):", dict_x)

print("Popped Value:", popped_value)

popped_item = dict_x.popitem()  # using popitem()

print("Updated Dictionary (Removed last item):", dict_x)

print("Popped Item:", popped_item)

dict_x.clear()  # using clear()

print("Update Dictionary (Removed all items):", dict_x)

Output:

Output

Given Dictionary: {'name': 'Sachin', 'age': 18, 'gender': 'male', 'profession': 'student', 'country': 'India'}

Updated Dictionary (Removed 'age'): {'name': 'Sachin', 'gender': 'male', 'profession': 'student', 'country': 'India'}

Updated Dictionary (Removed 'gender'): {'name': 'Sachin', 'profession': 'student', 'country': 'India'}

Popped Value: male

Updated Dictionary (Removed last item): {'name': 'Sachin', 'profession': 'student'}

Popped Item: ('country', 'India')

Update Dictionary (Removed all items): {}

Explanation:

In this illustration, we are presented with a dictionary. We have employed various techniques such as the del keyword, the pop method, the popitem method, and the clear method to eliminate items from the dictionary.

Changing Dictionary Items

In Python, we can modify the values of a dictionary item by accessing it through its corresponding key.

Python Example to Change Dictionary Items

Let’s examine a straightforward illustration to grasp how to modify dictionary entries in Python.

Example

Example

# simple example to change dictionary items

# given dictionary

dict_x = {

    "name": "Sachin",

    "age": 18,

    "gender": "male",

    "profession": "student",

    "country": "India"

    }

print("Given Dictionary:", dict_x)

# changing dictionary items

dict_x["age"] = 20

dict_x["profession"] = "developer"

print("Updated Dictionary:", dict_x)

Output:

Output

Given Dictionary: {'name': 'Sachin', 'age': 18, 'gender': 'male', 'profession': 'student', 'country': 'India'}

Updated Dictionary: {'name': 'Sachin', 'age': 20, 'gender': 'male', 'profession': 'developer', 'country': 'India'}

Explanation:

In this illustration, we have utilized the assignment operator to modify the values associated with the existing keys in the provided dictionary. Consequently, the items within the dictionary are refreshed.

Iterating Through a Dictionary

Beginning with Python version 3.7, dictionaries have become an ordered collection of elements; consequently, they preserve the sequence of their entries. We can traverse through the keys of a dictionary utilizing a 'for' loop, demonstrated in the example below.

Example

Example

# simple example to iterate through a dictionary

# given dictionary

dict_x = {

    "Name": "Sachin",

    "Age": 18,

    "Gender": "Male",

    "Profession": "Student",

    "Country": "India"

    }

print("Items in Dictionary:")

# iterating through a dictionary using for loop

for key in dict_x:

  value = dict_x[key]

  print(key, "->", value)

Output:

Output

Items in Dictionary:

Name -> Sachin

Age -> 18

Gender -> Male

Profession -> Student

Country -> India

Explanation:

In the example provided, we utilized the 'for' loop to traverse the keys within the dictionary and retrieved the corresponding value for each key.

Finding Length of a Dictionary

To ascertain the length of a dictionary, one can utilize Python's built-in function known as len. This function provides the total count of 'key: value' pairs that exist within the dictionary, enabling us to effectively gauge the size of the dictionary.

Python Example to Find the Length of a Dictionary

Consider the following illustration that demonstrates how the len function can be utilized to ascertain the size of a Python dictionary.

Example

Example

# simple example to determine length of a dictionary

# given dictionary

employees_info = {

    "John": "Sr. Software Developer",

    "Irfan": "UI/UX Designer",

    "Lucy": "Human Resource Manager",

    "Peter": "Team Lead",

    "Johnson": "Business Developer",

    }

print("Given Data:", employees_info)

# finding length of the dictionary

print("Size of Data:", len(employees_info))	# using len()

Output:

Output

Given Data: {'John': 'Sr. Software Developer', 'Irfan': 'UI/UX Designer', 'Lucy': 'Human Resource Manager', 'Peter': 'Team Lead', 'Johnson': 'Business Developer'}

Size of Data: 5

Explanation:

In the preceding illustration, the len function has been utilized to determine the total number of entries present within the specified dictionary.

Dictionary Membership Test

In Python, the 'in' and 'not in' operators can be utilized to determine if a particular key is present within a dictionary. Below is a straightforward example that demonstrates how to verify the existence of a given key in a Python dictionary.

Example

Example

# simple example to check membership

dict_y = {

    'fruit': 'apple',

    'vegetable': 'onion',

    'dry-fruit': 'resins'

}

# using 'in' and 'not in' operators

print("Is 'fruit' a member of 'dict_y'?:", 'fruit' in dict_y)

print("Is 'beverage' a member of 'dict_y'?:", 'beverage' in dict_y)

print("Is 'beverage' NOT a member of 'dict_y'?:", 'beverage' not in dict_y)

Output:

Output

Is 'fruit' a member of 'dict_y'?: True

Is 'beverage' a member of 'dict_y'?: False

Is 'beverage' NOT a member of 'dict_y'?: True

Explanation:

In this illustration, we have utilized the 'in' and 'not in' operators to determine whether the specified keys are included in the provided dictionary. The 'in' operator yields a Boolean value by verifying the presence of the key within the dictionary, while the 'not in' operator gives a Boolean value by confirming the absence of the key from it.

Dictionary Methods in Python

Python provides a variety of dictionary methods designed to facilitate the manipulation of dictionary data. These functions are frequently utilized for tasks such as adding, modifying, removing, and retrieving elements within dictionaries. Below are some examples of these methods:

Dictionary Method Description
get() This method returns the value associated with a specific key.
update() This method is utilized to add a new item to the dictionary or update the value of an existing key.
copy() This method is utilized to return a copy of the dictionary.
pop() This method removes the item with the given key from the dictionary.
popitem() This method is utilized to return the last inserted key and value as a tuple.
clear() This method removes all items from the dictionary.
keys() This method returns all the keys in the dictionary.
values() This method is utilized to return all the values in the dictionary.

Conclusion

Python dictionaries represent a core and versatile data structure that enables the storage, retrieval, and management of data through 'key: value' associations. They are designed for quick access and can accommodate a range of uses, from straightforward mappings to intricate nested structures. Whether you are dealing with configuration files, handling JSON data, or developing applications driven by data, having a solid understanding of dictionaries is crucial for crafting effective and organized code in practical situations.

Python Dictionary FAQs

1. What is a Python Dictionary?

A Python dictionary is a mutable and unordered collection of pairs in the form of 'key: value', where each key is distinct and linked to a value, enabling quick retrieval based on these keys.

2. What are the types of values we can store in a Python dictionary?

A dictionary can hold a wide variety of value types, such as integers, strings, lists, other dictionaries, and even user-defined objects. While there are no limitations on the types of values that can be stored, there are specific criteria that must be met regarding the keys used.

3. What types of data can we use as keys in a Python dictionary?

The keys utilized in a dictionary must be of immutable types. This implies that we can employ strings, numbers, and tuples as keys; conversely, lists and dictionaries cannot serve as keys since they are classified as mutable data types.

4. Can a dictionary in Python contain duplicate keys?

No. It is not permissible to utilize duplicate keys within a dictionary. When an attempt is made to add a key that already exists in the dictionary, the new value will replace the value that is currently associated with that key.

5. Can a Python dictionary have nested dictionaries?

Indeed. A dictionary can be nested, which means it is possible to include dictionaries as values within another dictionary. This approach is particularly beneficial for modeling intricate hierarchical data structures such as JSON responses or configuration files.

Input Required

This code uses input(). Please provide values below: