Master Python Dictionaries: Creation, Modification, and Common Operations
This tutorial explains Python dictionaries—how they are defined, their key characteristics, and step‑by‑step code examples for creating, updating, deleting, clearing, and comparing dictionaries, while highlighting version‑specific differences such as the removal of the cmp function.
This article is the second part of a series on Python data structures, focusing on dictionaries (dict), one of the most flexible built‑in container types.
Characteristics of dictionaries
Mutable container that can store objects of any type.
Key‑value pairs are written as key: value and separated by commas inside curly braces {}.
Keys must be unique and immutable (e.g., strings, numbers, tuples); values can be any type.
Accessed via keys rather than positional indices.
Unordered collection, unlike lists which are ordered.
Supports nesting, allowing dictionaries within dictionaries.
Creating, modifying, adding, clearing, and deleting
dict = {"class": "5", "name": "莉莉", "年龄": "12"}
print(dict) # {'class': '5', 'name': '莉莉', '年龄': '12'}
# Access a value
print(dict["name"]) # 莉莉
# Update a value
dict["class"] = "6"
# Add a new key‑value pair
dict["年龄"] = "7"
# Add another key‑value pair
dict["father"] = "wangxiao"
# Delete a specific key‑value pair
del dict["father"]
# Clear all contents
dict.clear()
print(dict) # {}
# Delete the dictionary itself
del dict
print(dict) # NameError: name 'dict' is not definedCommon dictionary operations
# Number of items
len(dict) # 3
# Convert to printable string
str(dict) # "{'class': '5', '年龄': '12', 'name': '莉莉'}"
# Iterate over keys and values
for key, value in dict.items():
print(key)
print(value)
# Get a value safely
dict.get("class") # '5'
# Check existence of a key (Python 3)
"class" in dict # True
# View keys, values, items
dict.keys() # dict_keys([...])
dict.values() # dict_values([...])
dict.items() # dict_items([...])
# Merge another dictionary
dict2 = {"mother": "feifei"}
dict.update(dict2)
# Remove a key and get its value
dict.pop("mother") # 'feifei'Comparison and version differences
In Python 2 the cmp() function could compare two dictionaries, but it was removed in Python 3. To compare dictionaries now, import operator and use operator.eq(dict1, dict2). The article demonstrates this change and shows how the result differs when a key’s value is altered.
The author notes that the previous article covered lists, and the next installment will explore immutable sequences (tuples), which offer additional capabilities beyond lists.
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.
ITPUB
Official ITPUB account sharing technical insights, community news, and exciting events.
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.
