Dict Tutorial 2

(date: 2025-10-25)

难度: 1

时长: 30 min

获承成员值 dict.get()

方括号法写起来直观:

dict[key]

但不能很好的解决 key 不存的的问题。如果要避免 key not in dict error,使用 get(key) :

dict.get('key', default_value)

Example 1:

students['unknown']
students.get('unknown', '未知')

Example 2:

注意下面的陷阱

data = {'name': 'Alice', 'age': None}

# 键存在但值为 None
print(data.get('age', '未知'))      # 输出: None

# 键不存在
print(data.get('gender', '未知'))   # 输出: '未知'

详见: Python dict.get(default) 陷阱:None 值不会触发默认值

loop with assignment

# Define an empty dictionary
my_dict = {}
 
# Define a list of keys and a list of values
keys = ['a', 'b', 'c']
values = [1, 2, 3]
 
# Loop through the keys and values
for i in range(len(keys)):
    # Add the key-value pair to the dictionary
    my_dict[keys[i]] = values[i]
 
# Print the resulting dictionary
print(my_dict)

dict.setdefault()

dict.setdefault() to Add keys to dictionary if not exists

#why/solved dict 为什么要用 setdefault(), 直接等号赋值为什么不行? set default works only if the key doesn’t already exist in the dictionary. If the key already exists, the setdefault() method returns the current value for that key without changing it. 不修改已有值

# Define a dictionary with some initial keys
my_dict = {'a': 1, 'b': 2}
 
# Define a list of keys and a list of values
keys = ['a', 'b', 'c']
values = [1, 2, 3]
 
# Loop through the keys and values
for i in range(len(keys)):
    # Add the key-value pair to the dictionary if the key doesn't already exist
    my_dict.setdefault(keys[i], values[i])
	
	# my_dict(keys[i]) = values[i]   #/// 这样写为什么不行?

 
# Print the resulting dictionary
print(my_dict)

Add tuple as key to dictionary

tuple is hashable for dict key

# Define a dictionary with a tuple key and a value
my_dict = {('a', 1): 'apple'}
 
# Access the value with a tuple key
print(my_dict[('a', 1)])
 
# Add a new key-value pair with a tuple key
my_dict[('b', 2)] = 'banana'
 
# Print the updated dictionary
print(my_dict)

dict comprehension

#toreview

# Define the original dictionary
my_dict = {'a': 1, 'b': 2, 'c': 3}
 
# Define a list of keys to add
keys_to_add = ['d', 'e', 'f']
 
# Define a value for the new keys
value = 0
 
# Create a new dictionary with the key-value pairs to add
new_dict = {key: value for key in keys_to_add}
 
# Use dictionary comprehension to add the new keys to the original dictionary
my_dict = {**my_dict, **new_dict}
 
# Print the updated dictionary
print(my_dict)

Dict方法总结

  • d.clear()

  • d.get([, ])

  • d.items()

  • d.keys()

  • d.values()

  • d.pop([, ])

  • d.popitem()

  • d.update()

References