Python : Dictionaries

Python dictionaries are a versatile and widely used data structure that allows you to store key-value pairs. They are mutable, unordered collections, meaning the elements are stored and accessed by their keys rather than their position. Here's an overview of Python dictionaries:

Creating a Dictionary


You can create a dictionary by enclosing key-value pairs within curly braces `{}`, separated by commas and with colons `:` separating keys and values.


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

Alternatively, you can use the `dict()` constructor and pass it key-value pairs as arguments.


my_dict = dict(key1="value1", key2="value2", key3="value3")
 

Accessing Elements


You can access the value associated with a key by using square brackets `[]` and providing the key.


print(my_dict["key1"])  # Output: value1
 

Adding and Modifying Elements


You can add new key-value pairs or modify existing ones by assigning a value to a new key or an existing key, respectively.


my_dict["key4"] = "value4"  # Adding a new key-value pair
my_dict["key2"] = "new_value"  # Modifying an existing value

 

Dictionary Methods


Python dictionaries come with a variety of built-in methods for performing operations such as adding, removing, or accessing elements, as well as retrieving keys and values.

  • keys()       : Returns a view of all the keys in the dictionary.
  • values()    : Returns a view of all the values in the dictionary.
  • items()      : Returns a view of all key-value pairs in the dictionary.
  • get()          : Returns the value associated with a specified key (or a default value if the key is not found).
  • pop()         : Removes and returns the value associated with a specified key.
  • popitem()  : Removes and returns the last key-value pair inserted into the dictionary.
  • clear()        : Removes all key-value pairs from the dictionary.

Iterating Over Dictionaries


You can iterate over dictionaries using a `for` loop to access keys, values, or key-value pairs.


Iterating over keys


for key in my_dict:
    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)

 

Checking Membership


You can check if a key exists in a dictionary using the `in` and `not in` operators.


if "key1" in my_dict:
    print("Key 'key1' exists in the dictionary")

 

Dictionary Comprehensions


Similar to list comprehensions, you can also use dictionary comprehensions to create dictionaries in a more concise manner.


my_dict = {key: key**2 for key in range(5)}
print(my_dict)  # Output: {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}

Python dictionaries are incredibly useful for storing and accessing data in a flexible manner.