转字符串
map_v1 = {"name": "张三", "age": 20, "sex": "男"}
print("转字符串: ", str(map_v1))
遍历
map_v1 = {"name": "张三", "age": 20, "sex": "男"}
for k, v in map_v1.items():
print("k: {} v:{} ".format(k, v))
key是否存在
map_v2 = {"name": "张三", "age": 23, "sex": "男", "home": "北京"}
print("key = name 是否存在: ", "name" in map_v2)
print("key = city 是否存在: ", "city" in map_v2)
获取key和val
map_v1 = {"name": "张三", "age": 20, "sex": "男"}
keys = map_v1.keys()
print("所有key:{} 类型: {}".format(keys, type(keys)))
print("转成list,在访问: ", list(keys)[0])
values = map_v1.values()
print("所有values:{} 类型: {}".format(values, type(values)))
重置map值
map_v1 = {"语文": 60, "英语": 40, "数学": 73}
keys = map_v1.keys()
newMap = map_v1.fromkeys(keys, 100)
print("重置map_v1值为100后: ", newMap)
list_v1 = ["张三", "李四", "王五"]
age_map = {}.fromkeys(list_v1, 18)
print("基于列表创建map: ", age_map)
字典合并
map_v1 = {"语文": 60, "英语": 40, "数学": 73}
map_v2 = {"化学": 50, "英语": 66}
map_v1.update(map_v2)
print("map_v1: ", map_v1)
删除元素
map_v0 = {"语文": 60, "英语": 40, "数学": 73, "化学": 50}
del map_v0["语文"]
map_v1 = {"语文": 60, "英语": 40, "数学": 73, "化学": 50}
map_v1.pop("语文")
print("删除 key=语文:", map_v1)
map_v2 = {"name": "张三", "age": 23, "sex": "男", "home": "北京"}
res = map_v2.popitem()
print("删除最后一对键和值->并返回: ", res)
print("删除最后map_v2: ", map_v2)
读取key
map_v2 = {"name": "张三", "age": 23, "sex": "男", "home": "北京"}
print("key存在,key:name value: {}".format(map_v2.get("name", "")))
print("key不存在,key:city value: {} ".format(map_v2.get("city", "未知")))