Dictionaries in Python

Python : Dictionaries

Dictionaries are an important data structure in Python, allowing us to store and retrieve data using keys instead of numeric indices.

Dictionaries Syntax:

Dictionaries are created using curly braces and each entry in the dictionary consists of a key-value pair separated by a colon (:). Multiple entries are separated by commas.

my_dict = {"name": "John", "age": 30, "city": "New York"}

Accessing Dictionary Values:

We can access the values of a dictionary by using its keys. To do this, we can use square brackets [] and provide the key as the index. For example:

print(my_dict["name"]) # output: "John"

Adding and Modifying Dictionary Entries:

To add a new entry to a dictionary or modify an existing one, we can simply assign a new value to the key. For example:

my_dict["occupation"] = "Programmer"
print(my_dict)

# output: {"name": "John", "age": 30, "city": "New York", "occupation": "Programmer"}

Looping Through a Dictionary:

We can loop through a dictionary using a for loop. By default, the loop will iterate through the keys of the dictionary. To access the corresponding values, we can use the key to access the value in the dictionary. For example:

// default loop will iterate through the keys of the dictionary.
for key in my_dict:
    print(key, my_dict[key])

// items() method to iterate through both keys and values
for key, value in my_dict.items():
    print(key, value)


# output for both loop
# name John
# age 30
# city New York
# occupation Programmer

Use Cases of Dictionary in Python

Dictionaries are used extensively in Python for a wide range of applications, including:

  • Storing configuration settings for applications.
  • Creating lookup tables for quick access to data.
  • Counting the frequency of words in a text document.
  • Storing data that is related in a structured way.

Conclusion:

Dictionaries are an essential data structure in Python that allow us to store and retrieve data using keys instead of numeric indices. By mastering dictionaries, you can greatly enhance your Python programming skills and increase your productivity in a wide range of applications.