How To Use Dictionary Object In Python Examples

Python dictionary plays a crucial role in many Python programs. In this article, we will explore Python dictionaries in detail, covering their basics, operations, and providing numerous examples to illustrate their usage.

1. What is a Dictionary in Python?

  1. A dictionary in Python is an unordered collection of key-value pairs.
  2. Each key in a dictionary is unique and associated with a specific value.
  3. Dictionaries are also known as “dicts” and are implemented using curly braces `{}` or the built-in `dict()` constructor.

2. Creating a Dictionary.

  1. To create a dictionary, you can use curly braces `{}` and separate key-value pairs with colons (`:`).
  2. Here’s a simple example:
    # Creating a dictionary
    my_dict = {"name": "John", "age": 30, "city": "New York"}
  3. Alternatively, you can create an empty dictionary and add key-value pairs incrementally:

    # Creating an empty dictionary
    my_dict = {}

3. Add An Item To The Dictionary Object.

  1. Add a dictionary item is very simple, below is an example.
    # Adding key-value pairs 
    my_dict["name"] = "John" 
    my_dict["age"] = 30 
    my_dict["city"] = "New York"

4. Accessing Dictionary Elements.

  1. You can access values in a dictionary by specifying the key in square brackets.
  2. If the key exists, it will return the associated value; otherwise, it will raise a `KeyError`.
    >>> print(my_dict["name1"])
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    KeyError: 'name1'
  3. Here’s how to access elements in a dictionary:
    # Accessing dictionary elements
    print(my_dict["name"]) # Output: John
    print(my_dict["age"]) # Output: 30
  4. To avoid raising a `KeyError` when accessing dictionary elements, you can use the `get()` method, which allows you to provide a default value if the key does not exist:

    >>> print(my_dict.get("name", "Jerry"))
    John
    >>>
    >>> print(my_dict.get("name1", "Jerry")) # "Jerry" is the default value for name & name1 if the key is not exist.
    Jerry
    >>>

5. Modifying Dictionary Elements.

  1. Dictionaries are mutable, meaning you can change their values and add new key-value pairs.
  2. To modify an existing value, simply reference the key and assign a new value:
    # Modifying a dictionary value
    my_dict["age"] = 31
  3. To add a new key-value pair, assign a value to a new key:

    # Adding a new key-value pair
    my_dict["job"] = "Engineer"

6. Delete An Item From Dictionary Object.

6.1 Use the `del` statement to delete a dictionary item.

  1. In Python, you can use the `del` statement to delete an item from a dictionary by specifying the key of the item you want to remove.
  2. Here’s an example of how you can use the `del` statement to delete a dictionary item:
    >>> # Create a dictionary
    >>> my_dict = {
    ...     "name": "John",
    ...     "age": 30,
    ...     "city": "New York"
    ... }
    >>>
    >>> # Delete an item with a specific key
    >>> del my_dict["age"]
    >>>
    >>> # Print the updated dictionary
    >>> print(my_dict)
    {'name': 'John', 'city': 'New York'}
    

7. Dictionary Methods and Operations.

  1. Python provides a variety of methods and operations to work with dictionaries:

7.1 `keys()`, `values()`, and `items()`

  1. `keys()`: Returns a list of all the keys in the dictionary.
  2. `values()`: Returns a list of all the values in the dictionary.
  3. `items()`: Returns a list of key-value pairs (tuples) in the dictionary.
  4. Example source code.
    >>> my_dict = {"name": "John", "age": 30, "city": "New York"}
    >>>
    >>> my_dict.keys()
    dict_keys(['name', 'age', 'city'])
    >>>
    >>> my_dict.values()
    dict_values(['John', 30, 'New York'])
    >>>
    >>> my_dict.items()
    dict_items([('name', 'John'), ('age', 30), ('city', 'New York')])

7.2 `pop()` and `popitem()`.

    1. `pop(key[, default])`: Removes the key-value pair associated with the given key. If the key is not found and a default value is provided, it returns the default value; otherwise, it raises a `KeyError`.
      >>> my_dict.pop('name')
      'John'
      >>>
      >>> my_dict
      {'age': 30, 'city': 'New York'}
    2. `popitem()`: Removes and returns an arbitrary key-value pair as a tuple. Useful when you want to remove and process items in an unordered manner.

      >>> my_dict = {"name": "John", "age": 30, "city": "New York"}
      >>>
      >>> my_dict.popitem()
      ('city', 'New York')
      >>>
      >>> my_dict
      {'name': 'John', 'age': 30}
      >>>
      >>> my_dict.popitem()
      ('age', 30)
      >>>
      >>> my_dict
      {'name': 'John'}

7.3 `update()`.

  1. `update(iterable)`: Updates the dictionary with elements from another dictionary or an iterable of key-value pairs.
    >>> my_dict = {"name": "John", "age": 30, "city": "New York"}
    >>>
    >>> new_data = {"hobby": "Reading", "age": 32}
    >>>
    >>> my_dict.update(new_data)
    >>>
    >>> my_dict
    {'name': 'John', 'age': 32, 'city': 'New York', 'hobby': 'Reading'}

7.4 `clear()`.

  1. `clear()`: Removes all key-value pairs from the dictionary, making it empty.
    >>> my_dict = {"name": "John", "age": 30, "city": "New York"}
    >>>
    >>> my_dict.clear()
    >>>
    >>> my_dict
    {}
    >>>

7.5 `copy()`.

  1. The copy() method creates a shallow copy of the dictionary. Changes made to the copy do not affect the original dictionary, and vice versa. Here’s an example:
    my_dict = {
        "name": "John",
        "age": 30,
    }
    
    copy_dict = my_dict.copy()
    
    copy_dict["age"] = 31
    
    print(my_dict)
    # Output: {'name': 'John', 'age': 30}
    
    print(copy_dict)
    # Output: {'name': 'John', 'age': 31}
    

7.6 `get(key, default)`.

  1. The get() method allows you to retrieve the value associated with a specific key.
  2. If the key does not exist in the dictionary, it returns a default value (which is None by default).
  3. Here’s an example:
    my_dict = {
        "name": "John",
        "age": 30,
        "city": "New York"
    }
    
    name = my_dict.get("name")
    country = my_dict.get("country", "USA")
    
    print(name)
    # Output: John
    
    print(country)
    # Output: USA

8. Dictionary Comprehensions.

  1. Similar to list comprehensions, Python allows you to create dictionaries using dictionary comprehensions.
  2. This concise syntax is particularly useful when you want to create dictionaries from existing sequences.
    >>> numbers = [1, 2, 3, 4, 5]
    >>>
    >>> squared_dict = {x: x**2 for x in numbers}
    >>>
    >>> squared_dict
    {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

9. Iterating Over a Dictionary.

  1. You can iterate over the keys, values, or items of a dictionary using `for` loops. Here are some examples:
  2. Example1, iterate the keys of a dictionary object.
    >>> my_dict = {"name": "John", "age": 30, "city": "New York"}
    >>> for key in my_dict:
    ...     print(key)
    ...
    name
    age
    city
  3. Example2, iterate the values of a dictionary object.
    >>> my_dict = {"name": "John", "age": 30, "city": "New York"}
    >>> for value in my_dict.values():
    ...     print(value)
    ...
    John
    30
    New York
  4. Example3, iterate the key-value pairs of a dictionary object.
    >>> for key, value in my_dict.items():
    ...     print(key, value)
    ...
    name John
    age 30
    city New York

10. Conclusion.

  1. Python dictionaries are versatile data structures that allow you to store and manipulate key-value pairs efficiently.
  2. They are fundamental to many Python applications, from data processing to building complex data structures.
  3. Understanding dictionaries and their operations is essential for any Python programmer.
  4. With this comprehensive guide and examples, you should now have a solid foundation for working with Python dictionaries in your own projects.

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.