Home » Data Science » Python » Dictionary in Python

Newly Updated Posts

Dictionary in Python

In this tutorial, we will learn Dictionary in Python:

In Python, a dictionary is a built-in data structure that allows you to store and retrieve key-value pairs. It is also known as an associative array, map, or hash table in other programming languages. Dictionaries are mutable, unordered, and can contain elements of different data types.

Here’s a basic overview of how dictionaries work in Python:

  1. Creating a Dictionary: You can create a dictionary by enclosing comma-separated key-value pairs within curly braces {} or by using the built-in dict() function. Here’s an example:
# Creating an empty dictionary
my_dict = {}

# Creating a dictionary with initial values
my_dict = {"key1": value1, "key2": value2, "key3": value3}

# Using the dict() function
my_dict = dict(key1=value1, key2=value2, key3=value3)

2. Accessing Values:

You can access the values in a dictionary by using the corresponding key within square brackets []. If the key does not exist, it will raise a KeyError exception. Alternatively, you can use the get() method to retrieve values, which returns None or a default value if the key is not found.

# Accessing values
value1 = my_dict["key1"]
value2 = my_dict.get("key2")

3. Modifying Values:

You can modify the value associated with a key by assigning a new value to it.

my_dict["key1"] = new_value

4. Adding and Removing Items:

To add a new key-value pair, simply assign a value to a new key. To remove an item, you can use the del statement or the pop() method.

# Adding items
my_dict["key4"] = value4

# Removing items
del my_dict["key3"]
value = my_dict.pop("key2")

5. Dictionary Methods:

Python dictionaries come with several useful methods, including keys(), values(), and items(). These methods return iterable views of the dictionary’s keys, values, and key-value pairs, respectively.

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

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

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

Dictionaries are highly flexible and efficient for quick key-based lookups. They are widely used in Python for various purposes, such as counting occurrences, caching results, or organizing data.