字典
dict={'one':1,'two':2,'three':3}
# 遍历1:
# 先取出Key
for key in dict:# 取出Key对应的valueprint(f"key:{key}---value:{dict[key]}")#遍历2,依次取出value
for value in dict.values():print(value)# 遍历3:依次取出key,value
for key,value in dict.items():print(f"key:{key} value:{value}")
dict_name={'one':'tom','two':'bob','three':'amy'}
print(f"dict_name中项数为:{len(dict_name)}")
print(f"dict_name中one对应的项为:{dict_name['one']}")
#d=[key]=??,将字典d中k键对应的项修改为??,若无对应键,则添加
dict_name['one']=123
dict_name['for']='jucy'
print(dict_name)
#移除元素
del dict_name['one']
print(f"dict_name删除one键后为:{dict_name}")
#将元素移除并返回
pop=dict_name.pop('two')
print(f"pop:{pop},dict_name:{dict_name}")
# 返回字典中所有的key
dict_name_keys=dict_name.keys()
print(f"dict_name_keys:{dict_name_keys}")#key in d : 如果d中存在键key则返回True,否则返回Falseprint('one'in dict_name) #False
print('three'in dict_name) #True
# 字典生成基本语法
# {字典key的表达式:字典value的表达式 for 表示key的变量,表示value的变量 in zip (可迭代对象,可迭代对象)}
name=["报警","火警","急救","投诉"]
number=[110,119,120,12315]
map={name:number for name,number in zip (name,number)}
print(map)
# 创建字典遍历函数
def inf():for num, inf, in check.items():print(f"num:{num} -> inf:{inf} ")print("-" * 500)# 一个公司有多名员工,统计员工信息
check={"0001":{"name":"Bob","age":20,"BG":"本科","sal":"8000"},"0002": {"name": "luck","age": 25,"BG": "硕士","sal": "12000"},"0003": {"name": "may","age": 30,"BG": "博士","sal": "20000"}
}#通过员工编号查询员工信息
num=input("请输入员工编号:")
print(f"员工编号为{num}的基本信息如下:\n"f"name:{check[num]['name']}\n"f"age:{check[num]['age']}\n"f"BG:{check[num]['BG']}\n"f"sal:{check[num]['sal']}")
print("-"*500)# 删除一个员工
del check['0001']
print("删除0001号员工后:")#调用字典遍历函数
inf()#增加一个员工
check['0004']={"name": "luck","age": 25,"BG": "硕士","sal": "12000"
}
print("增加0004号员工后:")
inf()# 修改员工信息
check["0004"]["name"]="lt"
check["0004"]["age"]=30
check["0004"]["BG"]="本科"
check["0004"]["sal"]="11000"
print("修改0004号员工信息后:")
inf()#遍历所有员工信息,将BG修改为保密
for key in check:check[key]["BG"]="保密"
print("将员工BG修改为保密后,最新员工信息如下:")
inf()