python高级变量VIII
- 合并字典
使用.update()方法合并字典
dictionary_02 = {"Name":"Tom","age":18}
temp_dictionary = {"Weight":88}
dictionary_02.update(temp_dictionary)
print(dictionary_02) # 输出{'Name': 'Tom', 'age': 18, 'Weight': 88}
- 清空字典
使用.clear()方法清空字典
dictionary_02 = {"Name":"Tom","age":18}
temp_dictionary = {"Weight":88}
dictionary_02.update(temp_dictionary)
print(dictionary_02) # 输出{'Name': 'Tom', 'age': 18, 'Weight': 88}
# 清空字典
dictionary_02.clear()
print(dictionary_02) # {}
- 遍历字典
使用for循环来遍历字典。因为字典中存储不同类型的数据,所以实际开发中遍历字典并不常用。
dictionary_02 = {"Name":"Tom","age":18}
temp_dictionary = {"Weight":88}
dictionary_02.update(temp_dictionary)
print(dictionary_02) # 输出{'Name': 'Tom', 'age': 18, 'Weight': 88}
for k in dictionary_02:print("%s %s" % (k,dictionary_02[k]))
输出:
{‘Name’: ‘Tom’, ‘age’: 18, ‘Weight’: 88}
Name Tom
age 18
Weight 88