Comprehensive Guide to Python Dictionaries: Creation, Access, Modification, Traversal, Comprehensions, and Advanced Techniques
This tutorial provides a thorough overview of Python dictionaries, covering their creation, key‑value access, addition, update, deletion, iteration, comprehensions, safe retrieval with get(), merging, sorting, built‑in functions, and unpacking for function arguments, all illustrated with clear code examples.
In the vast landscape of Python programming, dictionaries (dict) stand out as a flexible, mutable, and unordered collection of key‑value pairs that enable rapid data access and manipulation.
Basic usage : creating a dictionary and accessing values.
# Create a dictionary storing student scores
student_scores = {'Alice': 95, 'Bob': 88, 'Charlie': 92}
print(student_scores['Alice']) # Output: 95Add, update, and delete operations demonstrate how to modify the dictionary.
# Add a new entry
student_scores['David'] = 90
print(student_scores)
# Update a value
student_scores['Bob'] = 90
print(student_scores)
# Delete an entry
del student_scores['Charlie']
print(student_scores)Traversing a dictionary shows iteration over all key‑value pairs.
for name, score in student_scores.items():
print(f"{name} 的分数是 {score}")Dictionary comprehensions illustrate creating a new dictionary from an existing one.
original = {'a': 1, 'b': 2, 'c': 3}
squared = {k: v**2 for k, v in original.items()}
print(squared) # Output: {'a': 1, 'b': 4, 'c': 9}Safe access with get() provides a default value when a key is missing.
print(student_scores.get('Eve', 0)) # Eve not in dict, returns 0Updating and merging dictionaries combines two dictionaries.
new_scores = {'Eve': 98, 'Frank': 89}
student_scores.update(new_scores) # Merge new scores
print(student_scores)Key uniqueness demonstrates that later assignments overwrite earlier ones.
# Attempt to add duplicate key; the latter overwrites the former
scores = {'Alice': 95, 'Bob': 88, 'Alice': 98}
print(scores) # Output: {'Alice': 98, 'Bob': 88}Sorting a dictionary by value produces a new ordered mapping.
sorted_scores = {k: v for k, v in sorted(student_scores.items(), key=lambda item: item[1], reverse=True)}
print(sorted_scores)Built‑in functions and operators such as len() and in are used to query dictionary size and key existence.
print(len(student_scores)) # Dictionary length
print('Alice' in student_scores) # Check if key existsUnpacking dictionaries with the ** operator allows passing entries as function arguments.
def print_student_info(name, score):
print(f"{name}'s score is {score}")
info = {'name': 'Grace', 'score': 93}
print_student_info(**info) # Output: Grace's score is 93In conclusion, Python dictionaries are a powerful tool for data handling, offering a rich set of operations—from basic CRUD actions to advanced comprehensions, safe retrieval, merging, sorting, and unpacking—that make them indispensable in virtually any programming project.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
