标签:obb 遍历 value mil 设置 int 元组 aaa bsp
# 有序or无序:无序
# 可变or不可变:可变类型
print(my_dict[‘name‘])
print(my_dict[‘hobbies‘][0])
# 赋值
my_dict[‘sex‘] = ‘male‘
my_dict[‘age‘] = 20
注:如果键已存在,则会改变对应的值。
len(my_dict)
print(‘name‘ in my_dict)
删除指定的key及对应的value,并返回value的值
print(my_dict.pop(‘name‘))
print(my_dict.keys()) # 返回所有的key
print(my_dict.values()) # 返回所有的value
print(my_dict.items()) # 返回所有的键值对
for key in my_dict: # 默认遍历为key
print(key)
for key in my_dict.keys(): # 遍历key
print(key)
for value in my_dict.values(): # 遍历value
print(value)
for key,value in my_dict.items(): # 遍历键值对
print(key,‘:‘,value,sep=‘‘)
# 返回对应的value
print(my_dict.get(‘name‘))
# 如果不存在指定的key,默认返回None,第二个参数可设置返回值(200)
print(my_dict.get(‘aaa‘,200))
# 随机删除一对键值,将被删除的key和value在元组内返回
print(my_dict.popitem())
1 my_dict = { 2 ‘name‘: ‘yyh‘, 3 ‘age‘: 19, 4 ‘hobbies‘: [‘basketball‘, ‘running‘] 5 } 6 my_dict.update({‘sex‘: ‘male‘}) 7 print(my_dict)
>>>{‘name‘: ‘yyh‘, ‘age‘: 19, ‘hobbies‘: [‘basketball‘, ‘running‘], ‘sex‘: ‘male‘}
print(my_dict)
my_dict = {}.fromkeys([‘k1‘,‘k2‘,‘k3‘],[])
print(my_dict)
>>>
{‘name‘: ‘yyh‘, ‘age‘: 19, ‘hobbies‘: [‘basketball‘, ‘running‘]}
{‘k1‘: [], ‘k2‘: [], ‘k3‘: []}
my_dict = {
‘name‘: ‘yyh‘,
‘age‘: 19,
‘hobbies‘: [‘basketball‘, ‘running‘]
}
# 如果键已存在,值不会发生改变
res = my_dict.setdefault(‘name‘,‘jxx‘)
# 输出为 yyh
print(res)
# 如果键不存在,会新增
res = my_dict.setdefault(‘sex‘,‘male‘)
print(res)
print(my_dict)
标签:obb 遍历 value mil 设置 int 元组 aaa bsp
原文地址:https://www.cnblogs.com/panweiwei/p/12801104.html