python
  1. python-dictionaries

Python Dictionaries

Dictionaries are used to store data values in key:value pairs. A dictionary is a collection of unordered and changeable items where every item is a key:value pair. Dictionaries are written with curly brackets, and keys are separated from their values by a colon (:). The key, value pairs are separated by commas (,).

Syntax

The basic syntax for creating a dictionary in Python is:

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

Example

#creating a dictionary
employees = {
    "John": "CEO",
    "Alice": "Manager",
    "Bob": "Developer",
    "Charlie": "Designer"
}

#printing the dictionary
print(employees)

Output

{'John': 'CEO', 'Alice': 'Manager', 'Bob': 'Developer', 'Charlie': 'Designer'}

Explanation

The above example creates a dictionary named employees where the keys are employee names (in this case, John, Alice, Bob, and Charlie) and values are their job titles (CEO, Manager, Developer, and Designer).

Use

Dictionaries are commonly used for various purposes. Some of them are:

  • Storing data in key-value pairs: Dictionaries are frequently used when we have to store data values with a corresponding value.
  • Fast Lookup: When we want to search for a specific value, dictionaries provide a faster way to find it than lists.
  • Hash Tables: Dictionaries are implemented as hash tables in Python. Hashing reduces the complexity of managing and searching through the items.

Important Points

  • Dictionaries are mutable. We can add, remove and change items in a dictionary after it has been created.
  • Python dictionaries are unordered, so the order of the items in a dictionary is not guaranteed.

Summary

In this article, we learned about Python Dictionaries. We learned about the syntax for creating a dictionary, how to add elements to it and how to access them. We also learned about the various advantages of using dictionaries and their implementation in Python. Dictionaries are an essential data structure in Python, and it's important to understand how to use them effectively.

Published on: