dict={'one':1,'two':2,'three':3}
# 遍历1:
# 先取出Key
for key in dict:
# 取出Key对应的value
print(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,否则返回False
print('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)