python之dict

转字符串

map_v1 = {"name": "张三", "age": 20, "sex": "男"}
print("转字符串: ", str(map_v1))

# {'name': '张三', 'age': 20, 'sex': '男'}

遍历

map_v1 = {"name": "张三", "age": 20, "sex": "男"}
for k, v in map_v1.items():
    print("k: {} v:{} ".format(k, v))

# k:name v:张三 
# k:age v:20 
# k:sex v:男

key是否存在

map_v2 = {"name": "张三", "age": 23, "sex": "男", "home": "北京"}
print("key = name 是否存在: ", "name" in map_v2)
print("key = city 是否存在: ", "city" in map_v2)

# key = name 是否存在:  True
# key = city 是否存在:  False

获取key和val

map_v1 = {"name": "张三", "age": 20, "sex": "男"}
# 获取所有key
keys = map_v1.keys()
print("所有key:{} 类型: {}".format(keys, type(keys)))
# 转成list在访问
print("转成list,在访问: ", list(keys)[0])
# 获取所有val
values = map_v1.values()
print("所有values:{} 类型: {}".format(values, type(values)))

# 所有key:dict_keys(['name', 'age', 'sex']) 类型: 
# 转成list,在访问:  name
# 所有values:dict_values(['张三', 20, '男']) 类型: 

重置map值

map_v1 = {"语文": 60, "英语": 40, "数学": 73}
keys = map_v1.keys()
# 重置map_v1的值
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_v1:  {'语文': 60, '英语': 66, '数学': 73, '化学': 50}

删除元素


# 使用del关键字
map_v0 = {"语文": 60, "英语": 40, "数学": 73, "化学": 50}
del map_v0["语文"]
# 删除指定的key
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=语文: {'英语': 40, '数学': 73, '化学': 50}
# 删除最后一对键和值->并返回:  ('home', '北京')
# 删除最后map_v2:  {'name': '张三', 'age': 23, 'sex': '男'}

读取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", "未知")))

# key存在,key:name value: 张三
# key不存在,key:city value: 未知

你可能感兴趣的:(python,python)