杰瑞科技汇

Python中List、HashMap与Dict如何选择使用?

Of course! In Python, you don't have a data structure called ListHashmap. Instead, you use the built-in dict (dictionary), which is the standard and highly efficient implementation of a hash map.

Python中List、HashMap与Dict如何选择使用?-图1
(图片来源网络,侵删)

Here’s a complete guide covering everything from the basics to advanced use cases.

What is a Hash Map (Dictionary) in Python?

A dictionary is a collection of key-value pairs. It's an unordered (until Python 3.6, technically ordered by insertion since 3.7+) and mutable data structure.

  • Key: A unique identifier for a value. Keys must be immutable (e.g., strings, numbers, tuples). They cannot be lists or other dictionaries.
  • Value: The data associated with a key. Values can be of any data type, including other lists or dictionaries.

The "hash map" part refers to how Python stores data. It uses a hash function to compute an index (a hash) for each key, allowing for extremely fast lookups, insertions, and deletions, on average O(1) time complexity.


Creating a Dictionary

You can create dictionaries in several ways:

Python中List、HashMap与Dict如何选择使用?-图2
(图片来源网络,侵删)

a) Using Curly Braces

This is the most common method.

# An empty dictionary
empty_dict = {}
# A dictionary with key-value pairs
student = {
    "name": "Alice",
    "age": 25,
    "courses": ["Math", "Science"]
}
print(student)
# Output: {'name': 'Alice', 'age': 25, 'courses': ['Math', 'Science']}

b) Using the dict() Constructor

You can create a dictionary from a list of tuples, where each tuple contains a key-value pair.

# From a list of key-value tuples
person = dict([
    ("first_name", "Bob"),
    ("last_name", "Builder"),
    ("is_builder", True)
])
print(person)
# Output: {'first_name': 'Bob', 'last_name': 'Builder', 'is_builder': True}

You can also pass keyword arguments to the dict() constructor.

# From keyword arguments
another_person = dict(first_name="Charlie", last_name="Chaplin", is_actor=True)
print(another_person)
# Output: {'first_name': 'Charlie', 'last_name': 'Chaplin', 'is_actor': True}

Accessing, Adding, and Updating Items

Accessing Values

Use square brackets [] with the key. If the key doesn't exist, it will raise a KeyError.

Python中List、HashMap与Dict如何选择使用?-图3
(图片来源网络,侵删)
student = {"name": "Alice", "age": 25}
# Get a value
print(student["name"])
# Output: Alice
# This will raise a KeyError
# print(student["address"])

To avoid errors, use the .get() method. It returns None (or a default value you specify) if the key is not found.

# Safely get a value
print(student.get("age"))
# Output: 25
print(student.get("address"))
# Output: None
# Provide a default value
print(student.get("address", "Not specified"))
# Output: Not specified

Adding and Updating Items

You can add a new key-value pair or update an existing one using the same syntax.

student = {"name": "Alice", "age": 25}
# Add a new key-value pair
student["major"] = "Computer Science"
print(student)
# Output: {'name': 'Alice', 'age': 25, 'major': 'Computer Science'}
# Update an existing key's value
student["age"] = 26
print(student)
# Output: {'name': 'Alice', 'age': 26, 'major': 'Computer Science'}

Removing Items

Use the del statement or the .pop() method.

student = {"name": "Alice", "age": 26, "major": "Computer Science"}
# Remove a specific key-value pair using del
del student["major"]
print(student)
# Output: {'name': 'Alice', 'age': 26}
# Remove and return a value using pop
age = student.pop("age")
print(f"Removed age: {age}")
print(student)
# Output:
# Removed age: 26
# {'name': 'Alice'}

Common Dictionary Methods

Here are some of the most useful methods:

  • .keys(): Returns a view object of all keys.
  • .values(): Returns a view object of all values.
  • .items(): Returns a view object of all key-value pairs as tuples.
  • .clear(): Removes all items from the dictionary.
  • .copy(): Returns a shallow copy of the dictionary.
student = {"name": "Alice", "age": 26}
# Get keys, values, and items
print("Keys:", student.keys())
# Output: Keys: dict_keys(['name', 'age'])
print("Values:", student.values())
# Output: Values: dict_values(['Alice', 26])
print("Items:", student.items())
# Output: Items: dict_items([('name', 'Alice'), ('age', 26)])
# Create a copy
student_copy = student.copy()
student_copy["name"] = "Alicia"
print("Original:", student)
print("Copy:", student_copy)
# Output:
# Original: {'name': 'Alice', 'age': 26}
# Copy: {'name': 'Alicia', 'age': 26}

Iterating Over a Dictionary

You can easily loop through a dictionary's keys, values, or items.

student = {"name": "Alice", "age": 26, "major": "Computer Science"}
# Iterate over keys (this is the default behavior)
print("Keys:")
for key in student:
    print(key)
# Output:
# Keys:
# name
# age
# major
# Iterate over values
print("\nValues:")
for value in student.values():
    print(value)
# Output:
# Values:
# Alice
# 26
# Computer Science
# Iterate over key-value pairs (most common)
print("\nItems:")
for key, value in student.items():
    print(f"{key}: {value}")
# Output:
# Items:
# name: Alice
# age: 26
# major: Computer Science

Dictionary Comprehensions

This is a powerful and concise way to create dictionaries, similar to list comprehensions.

# Create a dictionary of squares
numbers = [1, 2, 3, 4, 5]
squares = {num: num * num for num in numbers}
print(squares)
# Output: {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
# Create a dictionary with condition
even_squares = {num: num * num for num in numbers if num % 2 == 0}
print(even_squares)
# Output: {2: 4, 4: 16}

Advanced: Lists of Dictionaries (The "ListHashmap" Analogy)

Often, you'll find yourself working with a list where each element is a dictionary. This is a very common pattern for representing structured data, like rows from a database or records from an API.

Let's say you want to find the student named "Alice".

# A list of dictionaries (our "list of hashmaps")
students = [
    {"id": 1, "name": "Alice", "age": 25, "major": "Computer Science"},
    {"id": 2, "name": "Bob", "age": 22, "major": "Physics"},
    {"id": 3, "name": "Charlie", "age": 24, "major": "Math"},
    {"id": 4, "name": "Alice", "age": 23, "major": "Art"} # Another Alice
]
# --- Finding all students named "Alice" ---
alices = [student for student in students if student["name"] == "Alice"]
print("All Alices:")
print(alices)
# Output:
# All Alices:
# [{'id': 1, 'name': 'Alice', 'age': 25, 'major': 'Computer Science'}, {'id': 4, 'name': 'Alice', 'age': 23, 'major': 'Art'}]
# --- Getting the names of all students ---
all_names = [student["name"] for student in students]
print("\nAll student names:")
print(all_names)
# Output:
# All student names:
# ['Alice', 'Bob', 'Charlie', 'Alice']
# --- Finding a specific student by ID (e.g., the first one with id=3) ---
student_id_3 = next((student for student in students if student["id"] == 3), None)
print("\nStudent with ID 3:")
print(student_id_3)
# Output:
# Student with ID 3:
# {'id': 3, 'name': 'Charlie', 'age': 24, 'major': 'Math'}

Summary: dict vs. ListHashmap Concept

Feature Python dict (Dictionary) Conceptual "ListHashmap"
Purpose A single collection of unique keys mapping to values. A collection of hash maps (i.e., a list of dictionaries).
Structure {key1: value1, key2: value2} [{key1: val1, ...}, {key2: val2, ...}]
Access my_dict['key'] my_list_of_dicts[index]['key'] or [d for d in my_list if d['key'] == value]
Use Case Storing properties of a single object (e.g., one user's profile). Storing a collection of similar objects (e.g., a list of all users).
分享:
扫描分享到社交APP
上一篇
下一篇