Translate

Friday 23 February 2024

Dictionaries In Python - Python Data Analyst

 


Dictionaries: The Key-Value Powerhouse

  • Unordered: Unlike lists and tuples, the order of items in a dictionary is not guaranteed.

  • Mutable: You can add, remove, and change key-value pairs after a dictionary is created.

  • Key-Value Pairs: Dictionaries store items as key-value pairs.

  • Keys: Must be immutable types (strings, numbers, tuples). They need to be unique within the dictionary.

  • Values: Can be of any data type (strings, numbers, lists, even other dictionaries!).

Creating Dictionaries

  1. Curly Braces: The most common method.
    Python
    student = {"name": "Alice", "age": 25, "courses": ["Math", "Science"]}

  2. dict() Constructor: You can create a dictionary from a sequence of key-value pairs or keyword arguments.
    Python
    # From key-value pairs
    phonebook = dict([("Alice", 123456), ("Bob", 789012)])

    # Using keyword arguments
    empty_dict = dict()

Accessing and Modifying Values

  • Accessing by Key: Use square brackets with the key.
    Python
    name = student["name"# Accessing the 'name' value

  • Adding/Modifying: Assign a value to a key.
    Python
    student["city"] = "New York"  # Adds a new key-value pair
    student["age"] = 26  # Modifies the 'age' value

  • Removing Items: Use the del keyword or the pop() method.
    Python
    del student["courses"]
    removed_value = student.pop("city"

Common Operations

  • in and not in: Check if a key exists in the dictionary.

  • len(dict): Returns the number of key-value pairs in the dictionary.

  • dict.keys(): Returns a view of the dictionary's keys.

  • dict.values(): Returns a view of the dictionary's values.

  • dict.items(): Returns a view of the key-value pairs as tuples.

Why Use Dictionaries?

  • Fast Lookups by Key: Dictionaries are optimized for quickly retrieving values based on their keys.

  • Representing Structured Data: Dictionaries excel at storing data that is naturally associated with labels or identifiers (like product information, user profiles, etc.).

Example


Python

employee = {
    "id": 12345,
    "name": "John Smith",
    "department": "Sales",
    "skills": ["communication", "negotiation", "teamwork"]
}

print("Employee Name:", employee["name"])

# Add a new skill
employee["skills"].append("data analysis")

Let's Recap

Dictionaries are powerhouses for organizing and working with structured data in Python. Remember:

  • They are unordered collections of key-value pairs.

  • Keys must be unique and immutable.

  • Values can be of any data type.



Key Methods for Dictionaries

  • dict.clear() Removes all key-value pairs from the dictionary, leaving it empty.
    Python
    shopping_list = {"apples": 2, "bananas": 5}
    shopping_list.clear()  # shopping_list is now {}

  • dict.copy() Creates a shallow copy of the dictionary.
    Python
    original = {"name": "Alice", "city": "London"}
    new_dict = original.copy() 

  • dict.fromkeys(keys, value=None) Creates a new dictionary with keys from an iterable and sets the value of each key to the specified value (or None if no value is provided).
    Python
    colors = ["red", "green", "blue"]
    color_ratings = dict.fromkeys(colors, 0# {'red': 0, 'green': 0, 'blue': 0}

  • dict.get(key, default=None) Returns the value associated with a key. If the key is not found, it returns the default value (or None if no default is specified).
    Python
    student = {"name": "Bob", "age": 20}
    city = student.get("city"# city will be None

  • dict.items() Returns a view object containing (key, value) pairs as tuples. Use this to iterate over a dictionary's items.
    Python
    for key, value in student.items():
        print(f"{key}: {value}")

  • dict.keys() Returns a view object containing the keys of the dictionary.
    Python
    for key in student.keys():
        print(key)

  • dict.pop(key, default=None) Removes the key-value pair with the specified key and returns its value. Raises a KeyError if the key is not found, or returns the default value if provided.
    Python
    removed_age = student.pop("age"

  • dict.popitem() Removes and returns an arbitrary (key, value) pair from the dictionary. Useful when you don't care about the specific key removed.

  • dict.setdefault(key, default=None) Similar to get(), but if the key isn't found, it inserts the key with the default value and returns that value.
    Python
    counts = {}
    word = "hello"
    counts.setdefault(word, 0# If 'hello' doesn't exist, create it with value 0
    counts[word] += 1

  • dict.update(other) Updates the dictionary with key-value pairs from another dictionary (other), overwriting any existing keys.
    Python
    student1 = {"name": "Alice"}
    student2 = {"age": 25, "city": "New York"}
    student1.update(student2)  # student1 now becomes {"name": "Alice", "age": 25, "city": "New York"}

  • dict.values() Returns a view object containing the values of the dictionary.

Let's see an Example


Python

prices = {"apple": 1.50, "banana": 0.75, "orange": 1.25}
inventory = {"apple": 20, "banana": 15}

# Calculate total value of inventory
total_value = 0
for item, price in prices.items():
    quantity = inventory.get(item, 0# Get quantity, defaulting to 0 if not found
    total_value += price * quantity

print("Total inventory value:", total_value)

Key Points

  • Most of these methods return "views" into the dictionary, which are dynamic representations and reflect changes you make to the dictionary.

 Python dictionaries.

Example 1: Student Records


Python

students = {
    "1001": {"name": "Alice", "major": "Computer Science", "grades": [85, 92, 78]},
    "1002": {"name": "Bob", "major": "Biology", "grades": [90, 87, 94]},
    "1003": {"name": "Charlie", "major": "Business", "grades": [76, 80, 88]}
}

def calculate_average(student_id):
    student = students.get(student_id)
    if student:
        average = sum(student["grades"]) / len(student["grades"])
        print(f"{student['name']}'s average grade is: {average}")
    else:
        print("Student not found.")

calculate_average("1002"# Calculate average for Bob
calculate_average("1005"# Handle invalid student ID

  • Why dictionaries? Dictionaries model the real-world concept of a

  • student record well.

  • Each student has unique attributes (name, major, grades) associated

  • with their ID.

Example 2: Word Frequency Counter


Python

text = "This is a sample text. This text contains

some repeated words."

word_counts = {}
for word in text.lower().split():
    word_counts[word] = word_counts.get(word, 0) + 1

print("Word Counts:")
for word, count in word_counts.items():
    print(f"{word}: {count}")

  • Why dictionaries? The dictionary naturally stores each unique

  • word (the key) and its corresponding count (the value).

Example 3: Phone Book


Python

phonebook = {
    "Alice": "(123) 456-7890",
    "Bob": "(987) 654-3210",
    "Eve": "(555) 123-4567"
}

# Add a new contact
phonebook["Jane"] = "(321) 987-6540"

# Lookup a number
name = input("Enter name: ")
number = phonebook.get(name)
if number:
    print(f"{name}'s number: {number}")
else:
    print("Contact not found.")

  • Why dictionaries? Dictionaries provide fast lookups by name,

  • perfect for phone book functionality!

Key Points:

  • Dictionaries excel at storing structured data where you need

  • fast lookups by unique keys.

  • They can model the relationship between real-world entities

  • and their attributes.



-----------------------

Conceptual Questions

  • Q: Describe what dictionaries are in Python and how they differ from lists.

  • A: Dictionaries are unordered collections of key-value pairs. Keys must be unique and immutable (e.g., strings, numbers, tuples), while values can be of any data type. This contrasts with lists, which are ordered collections where elements are accessed by their index.

  • Q: Explain why keys in a dictionary need to be immutable.

  • A: Keys need to be immutable (unchangeable) because dictionaries use a technique called "hashing" to quickly look up values. If a key could change, its hash value would change, and the dictionary wouldn't be able to locate the correct value.

  • Q: In what scenarios would you choose to use a dictionary over a list?

  • A: Use a dictionary when:

  • You need to store data associated with specific labels or identifiers (e.g., product information, employee records).

  • Fast lookups by a unique key are important.

  • The order of elements doesn't matter.

Operations and Functionality

  • Q: How do you add a new key-value pair to an existing dictionary?

  • A: Simply assign a value to a new key: my_dict["new_key"] = "value". If the key already exists, its value will be updated.

  • Q: What's the difference between the get() and pop() methods of a dictionary?

  • A:

  • get(key, default=None) retrieves the value associated with a key. If the key isn't found, it returns the default value (or None if not specified).

  • pop(key, default=None) removes the key-value pair and returns the value. Raises a KeyError if the key is not found, or returns the default if provided.

  • Q: How do you iterate through the keys and values of a dictionary?

  • A: Use the items() method for both keys and values:
    Python
    for key, value in my_dict.items():
        print(key, ":", value)
    To iterate over keys only, use my_dict.keys(). Similarly, use my_dict.values() for just values.

Problem-Oriented Scenarios

  • Q: You're given a list of words. How would you calculate the frequency of each word using a dictionary?

  • A:

  1. Create an empty dictionary word_counts.

  2. Iterate through the words.

  3. For each word, use word_counts.get(word, 0) + 1 to increment its count, taking advantage of get's default behavior.

  • Q: You have two dictionaries, and you want to merge them into a single dictionary. How would you do this?

  • A:

  • In Python 3.5 and later: Use the ** unpacking operator for a concise solution: merged_dict = {**dict1, **dict2}.

  • For older versions, use the update() method: dict1.update(dict2). Note that this modifies dict1 in-place.

Tips for Success:

  • Clarity: Explain your answers in a structured way.

  • Examples: Use brief code snippets to demonstrate your points.

  • Tradeoffs: Sometimes, discuss potential alternatives (e.g., in some cases, lists with custom lookup logic might be considered but usually dictionaries are more efficient).





Dictionaries In Python - 15 Python Data Analyst

No comments:

Post a Comment

Note: only a member of this blog may post a comment.