Built with Tutify.io

    AIStudyLabs

    Dictionaries: Key-Value Storage

    Dictionaries: Key-Value Storage

    Introduction

    In this lesson on dictionaries, we will explore the versatile and powerful data structure of key-value pairs in Python. Dictionaries act as a primary method for storing and retrieving data efficiently using unique keys. This lesson will guide you through creating dictionaries using multiple constructors, manipulating dictionary items safely, leveraging different methods for data retrieval and updates, and implementing dictionaries in practical scenarios such as counting elements and mapping configurations.

    Creating Dictionaries

    Using Dictionary Literals

    The most straightforward way to create a dictionary is using curly braces {} to define key-value pairs.

    fruits = {'apple': 2.5, 'banana': 1.2, 'cherry': 3.0}
    

    Using the dict() Constructor

    An alternative is using the dict() constructor, which creates dictionaries from keyword arguments or iterable pairs.

    animal_ages = dict(cat=5, dog=7, turtle=40)
    

    From Sequences of Pairs

    You can also form dictionaries from tuples or lists of key-value pairs.

    pairs = [('name', 'Alice'), ('age', 25), ('city', 'New York')]
    person = dict(pairs)
    

    Accessing and Manipulating Dictionaries

    Accessing Values Safely

    Retrieve values for a specified key using the square bracket [] notation. Use get() when uncertain if a key exists, as it won't cause errors.

    print(person['name'])  # Direct access
    age = person.get('age')  # Safe access
    

    Inserting and Updating Elements

    Insert new items by assigning a value to a new key, or update the existing key.

    person['occupation'] = 'Engineer'  # Inserting
    person['age'] = 30  # Updating
    

    Deleting Key-Value Pairs

    Remove items with the del statement or pop() method. Use pop() to both remove and return the value.

    del person['city']  # Using del
    occupation = person.pop('occupation')  # Using pop()
    
    # Output
    # Alice is now 30 years old, and removed 'Engineer'
    

    Iterating Over Dictionaries

    Iterating Keys, Values, and Items

    Python provides efficient ways to iterate through keys, values, or items simultaneously.

    for key in person.keys():
        print(key)
    
    for value in person.values():
        print(value)
    
    for key, value in person.items():
        print(f"{key}: {value}")
    

    Utilizing Dictionary Methods

    Methods Overview

    Example of update():

    new_details = {'hobby': 'painting'}
    person.update(new_details)
    
    # Output
    # {'name': 'Alice', 'age': 30, 'hobby': 'painting'}
    

    Practical Applications

    Using Dictionaries for Counting Elements

    Dictionaries can efficiently count occurrences. Here’s a simple counting example:

    items = ['apple', 'banana', 'apple', 'orange', 'banana', 'apple']
    count = {}
    for item in items:
        count[item] = count.get(item, 0) + 1
    

    Lookups and Mapping

    Dictionaries allow fast lookups, ideal for mapping configurations or settings.

    default_colors = {'header': 'blue', 'text': 'black', 'background': 'white'}
    text_color = default_colors.get('text', 'default color')
    

    Summary / Key Takeaways

    In this lesson on Dictionaries: Key-Value Storage, you have learned:

    Python Programming – Complete Course with Practical Examples — Collections: Lists, Tuples, Sets, and Dictionaries

    Getting Started with Python and the Course

    Python Syntax, Indentation, and Core Concepts

    Variables, Data Types, and Type Conversion

    Operators, Expressions, and Control Flow

    Loops and Iteration Patterns

    Working with Strings in Depth

    Collections: Lists, Tuples, Sets, and Dictionaries

    Functions and Program Structuring

    Functional Programming Concepts in Python

    Modules, Packages, and Code Organization

    Error Handling and Debugging Fundamentals

    File Handling and Data Formats

    Object-Oriented Programming in Python

    Advanced Python: Iterators, Generators, and Decorators

    Python Standard Library for Real-World Tasks

    Python for Automation and Scripting

    Testing and Quality Assurance in Python

    Tutorial Not Found