Dictionary in Python


In Python, a dictionary is a collection of key-value pairs. It is an unordered, mutable, and indexed data type. Each key-value pair in a dictionary maps a unique key to a specific value. Dictionaries are optimized for fast lookups based on keys, making them ideal for scenarios where you need to associate values with unique identifiers.

Dictionary Definition

A dictionary is defined using curly braces {}, with key-value pairs separated by a colon : and individual pairs separated by commas.

Syntax:

  • dictionary_name = {key1: value1, key2: value2, key3: value3, ...}


Creating a Dictionary

  • # Example of a dictionary with strings as keys and integers as values

  • person = {"name": "Alice", "age": 25, "city": "New York"}


  • # Dictionary with mixed data types

  • mixed_dict = {"name": "John", "age": 30, "is_student": True, "scores": [90, 85, 88]}


  • # Dictionary with tuple as keys

  • tuple_dict = {("x", "y"): 1, ("a", "b"): 2}


Accessing Values in a Dictionary

You can access dictionary values using the corresponding key inside square brackets [] or with the get() method.

Using Square Brackets:

  • person = {"name": "Alice", "age": 25, "city": "New York"}

  • print(person["name"])  # Output: Alice

  • print(person["age"])   # Output: 25


Using get() Method:

The get() method is useful when you're unsure if the key exists, as it returns None if the key doesn't exist, rather than raising an error.

  • print(person.get("name"))   # Output: Alice

  • print(person.get("country"))  # Output: None (key does not exist)


Modifying a Dictionary

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

Adding or Modifying Values:

  • person = {"name": "Alice", "age": 25, "city": "New York"}


  • # Modify an existing key-value pair

  • person["age"] = 26  # Changes age to 26


  • # Add a new key-value pair

  • person["country"] = "USA"


  • print(person)


Output:

  • {'name': 'Alice', 'age': 26, 'city': 'New York', 'country': 'USA'}


Removing Items from a Dictionary

You can remove items using several methods:

  • del keyword: Removes a specific key-value pair by key.

  • pop() method: Removes the item with the specified key and returns the corresponding value.

  • popitem() method: Removes and returns an arbitrary key-value pair (useful for popping elements in a LIFO manner).

  • clear() method: Removes all items from the dictionary.

Using del Keyword:

  • person = {"name": "Alice", "age": 25, "city": "New York"}

  • del person["city"]  # Removes the "city" key-value pair

  • print(person)


Output:

  • {'name': 'Alice', 'age': 25}


Using pop() Method:

  • removed_value = person.pop("age")  # Removes "age" and returns its value

  • print(removed_value)  # Output: 25

  • print(person)  # Output: {'name': 'Alice'}


Using popitem() Method:

  • person = {"name": "Alice", "age": 25, "city": "New York"}

  • removed_item = person.popitem()  # Removes the last item (in Python 3.7+, dicts are ordered)

  • print(removed_item)  # Output: ('city', 'New York')

  • print(person)  # Output: {'name': 'Alice', 'age': 25}


Using clear() Method:

  • person = {"name": "Alice", "age": 25}

  • person.clear()  # Removes all items

  • print(person)  # Output: {}


Dictionary Keys and Values

You can retrieve just the keys, values, or both using the keys(), values(), and items() methods, respectively.

Using keys() Method:

  • person = {"name": "Alice", "age": 25, "city": "New York"}

  • keys = person.keys()

  • print(keys)  # Output: dict_keys(['name', 'age', 'city'])


Using values() Method:

  • values = person.values()

  • print(values)  # Output: dict_values(['Alice', 25, 'New York'])


Using items() Method:

  • items = person.items()

  • print(items)  # Output: dict_items([('name', 'Alice'), ('age', 25), ('city', 'New York')])


Looping Through a Dictionary

You can loop through a dictionary using a for loop to access its keys, values, or both.

Loop Through Keys:

  • person = {"name": "Alice", "age": 25, "city": "New York"}

  • for key in person:

  •     print(key)


Output:

  • name

  • age

  • city


Loop Through Values:

  • for value in person.values():

  •     print(value)


Output:

  • Alice

  • 25

  • New York


Loop Through Key-Value Pairs:

  • for key, value in person.items():

  •     print(key, value)


Output:

  • name Alice

  • age 25

  • city New York


Nested Dictionaries

A dictionary can contain other dictionaries, creating nested dictionaries.

  • person = {

  •     "name": "Alice",

  •     "address": {

  •         "street": "123 Main St",

  •         "city": "New York",

  •         "zip": "10001"

  •     }

  • }

  • print(person["address"]["city"])  # Output: New York


Dictionary Comprehensions

You can create dictionaries using a dictionary comprehension similar to list comprehensions.

Syntax:

  • {key_expression: value_expression for item in iterable}


Example:

  • squares = {x: x**2 for x in range(5)}

  • print(squares)


Output:

  • {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}


Merging Dictionaries

You can merge dictionaries using the update() method or the | (union) operator in Python 3.9+.

Using update() Method:

  • dict1 = {"name": "Alice", "age": 25}

  • dict2 = {"city": "New York", "country": "USA"}

  • dict1.update(dict2)  # Merges dict2 into dict1

  • print(dict1)


Output:

  • {'name': 'Alice', 'age': 25, 'city': 'New York', 'country': 'USA'}


Using | Operator (Python 3.9+):

  • dict1 = {"name": "Alice", "age": 25}

  • dict2 = {"city": "New York", "country": "USA"}

  • merged_dict = dict1 | dict2  # Creates a new merged dictionary

  • print(merged_dict)


Output:

  • {'name': 'Alice', 'age': 25, 'city': 'New York', 'country': 'USA'}


Use Cases for Dictionaries

  • Mapping and Lookups: Dictionaries are ideal for scenarios where you need to map unique keys to specific values, such as representing data records, configurations, or counting occurrences of items.

  • Fast Access: Dictionaries provide O(1) time complexity for key lookups, making them efficient for tasks requiring frequent access to data by key.

Conclusion:

  • Dictionaries are a powerful and flexible data type in Python that store key-value pairs.

  • They are mutable, unordered, and allow fast access to data.

  • You can perform operations like adding, modifying, removing items, and iterating over keys, values, and key-value pairs.

Let me know if you'd like further examples or have any more questions! 😊


Post a Comment

0 Comments