Python Basics: Dictionaries – Access, Iterate, Merge, and Set Operations
This tutorial walks through essential Python data structures, showing how to retrieve a dictionary's length, keys, values, and items, iterate using four different patterns, merge dictionaries with update, and then introduces sets—covering creation, properties, and common operations such as add, update, pop, remove, discard, clear, and iteration—with concrete code examples and their outputs.
Dictionary Operations
The article demonstrates basic dictionary handling in Python. It creates a dictionary
dict1 = {'name':'中国医生','author':'张三','person':'李四','address':'china'}and shows how to obtain its length with len(dict1), retrieve all keys, values, and items, and prints the results.
dict1 = {'name':'中国医生','author':'张三','person':'李四','address':'china'}
print(len(dict1))
print(dict1.keys())
print(dict1.values())
print(dict1.items())Four iteration methods are illustrated:
# 1. Iterate over keys
for i in dict1:
print(i)
# 2. Enumerate keys
for k, v in enumerate(dict1):
print(k, v)
# 3. Iterate over key‑value pairs
for k, v in dict1.items():
print(k, v)
# 4. Iterate over values
for v in dict1.values():
print(v)Dictionary merging is shown using update. Two dictionaries are defined: dict2 = {"name":"成龙","sex":"男","age":61} and dict3 = {'address':'香港'}. After dict2.update(dict3), the combined dictionary is printed.
dict2 = {"name":"成龙","sex":"男","age":61}
dict3 = {'address':'香港'}
dict2.update(dict3)
print(dict2)Set Operations
The article then introduces Python sets, emphasizing that they are unordered collections without duplicate elements. A set is created with mixed types:
set1 = {12,34,5,67,True}
print(set1)
print(type(set1))Common set methods are demonstrated:
Getting the length with len(set1).
Adding elements one at a time using set1.add(98) and set1.add(57).
Adding multiple elements with set1.update([76,2,3]).
print(len(set1))
set1.add(98)
set1.add(57)
print(set1)
set1.update([76,2,3])
print(set1)Removal operations are covered using a second set set2 = {23,45,67,8,90,87}: set2.pop() removes an arbitrary element. set2.remove(45) deletes a specific element (raises an error if absent). set2.discard(8) safely deletes an element without error. set2.clear() empties the set.
set2 = {23,45,67,8,90,87}
set2.pop()
print(set2)
set2.remove(45)
set2.discard(8)
set2.clear()
print(set2)Finally, the article shows how to iterate over a set:
for i in set2:
print(i)Each code block is followed by the corresponding output shown in the original article, confirming the behavior of the demonstrated operations.
Lisa Notes
Lisa's notes: musings on daily life, work, study, personal growth, and casual reflections.
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.
