python菜鸟学习: 6. 字典常用方法
# -*- coding: utf-8 -*-
dict1 = {"name": "liyuzhoupan", "age": "22", "level": "3"}
dict2 = {"name": "LiYuZhou", "age": "32", "level": "6", "students": True}
# 打印字典中所有键
print(dict1.keys())
# 打印所有的值
print(dict1.values())
# 字典合并,如果有一样键,则替换值
dict1.update(dict2)
print(dict1)
# 打印字典中的某个键对应的值
print(dict1["name"])
# 修改字典,如果没有则新增
dict1["name"] = "鲤鱼洲畔"
# 获取字典中是否有
print(dict1.get("name1"))
# 判断是否有name
print("name" in dict1)
# 将字典转换成列表
print(dict1.items())
# 初始化新字段,并附一个初始化的值
dict3 = dict.fromkeys([1, 2, 3], "test")
print(dict3)
# 字典遍历1,常用
for i in dict1:
print(i, dict1[i])
# 字典遍历2,数据量小的时候可以使用
for k, v in dict1.items():
print(k, v)
本文来自博客园,作者:鲤鱼洲畔,转载请注明原文链接:https://www.cnblogs.com/liyuzhoupan/p/16588491.html