注意字典中的元素是无序的 1 get() 根据key获取对应的值,key不存在默认取None v = { "k1":'v1', # 键值对 "k2":'v2', # 键值对 } val = v.get('k1') val2 =v.get('klffff','9999') #如果key不存在,则将设置为默
注意字典中的元素是无序的
1 get() 根据key获取对应的值,key不存在默认取None
v = {"k1":'v1', # 键值对
"k2":'v2', # 键值对
}
val = v.get('k1')
val2 =v.get('klffff','9999') #如果key不存在,则将设置为默认值,另默认值为None
val3 =v.get('k3333')
print(val)
print(val2)
print(val3)v1
9999
None
2 下面的方法是可与for循环一起使用
val=v.keys()print(val)
val=v.values()
print(val)
val=v.items()
print(val)dict_keys(['k1', 'k2'])
dict_values(['v1', 'v2'])
dict_items([('k1', 'v1'), ('k2', 'v2')])
3 dict 类中的公共方法
(1)取长度
(2)根据索引修改,取值,删除值
(3)for循环
- for a in v.keys()
- for a in v.values():
- for a,b in v.items():
# "k1":'v1', # 键值对
# "k2":'v2', # 键值对
# }
# 1. 获取字典长度(键值对的个数)
# val = len(v)
# print(val)
# 2. 索引
# - 获取
# val = v['k1'] # k1不存在会报错,v.get('k1') 也能取值,且不会报错
# print(val)
# -设置
# key存在,则更新值
# key不存在,则创建键值对
# v['kk1'] = 666
# - 删除
# del v['k1']
# 3. for循环
# v = {
# "k1":'v1', # 键值对
# "k2":'v2', # 键值对
# }
#
# for i in v:
# print(i)
# for i in v.keys():
# print(i)
# for i in v.values():
# print(i)
# key,value
# for i in v.keys():
# print(i,v[i]) # "k1"
# for a,b in v.items():
# print(a,b)
4 dict中的补充方法
(1)copy() deepcopy() 深浅拷贝
'k1': 'v1',
'k2': [11,22,33,44]
}
dic2 = dic1.copy()
print(dic1,dic2)
dic1['k2'].append(666)
print(dic1,dic2)
dic1 = {
'k1': 'v1',
'k2': [11,22,33,44]
}
import copy
dic2 = copy.deepcopy(dic1)
print(dic1,dic2)
dic1['k2'].append(666)
print(dic1,dic2){'k1': 'v1', 'k2': [11, 22, 33, 44]} {'k1': 'v1', 'k2': [11, 22, 33, 44]}
{'k1': 'v1', 'k2': [11, 22, 33, 44, 666]} {'k1': 'v1', 'k2': [11, 22, 33, 44, 666]}
{'k1': 'v1', 'k2': [11, 22, 33, 44]} {'k1': 'v1', 'k2': [11, 22, 33, 44]}
{'k1': 'v1', 'k2': [11, 22, 33, 44, 666]} {'k1': 'v1', 'k2': [11, 22, 33, 44]}
(2)pop() 删除指定key 的键值对
dic = {'k1':'v1','k2':'v2'}v = dic.pop('k23','默认值') #删除不存在字典中的key则为默认值,与list中pop方法类似
print(dic)
print(v){'k1': 'v1', 'k2': 'v2'}
默认值
(3)popitem() 注意字典无序,随机删除一个
dic = {'k1':'v1','k2':'v2'}v1,v2 = dic.popitem()
print(dic)
print(v1,v2){'k1': 'v1'}
k2 v2
(4)setdefault()
dic = {'k1':'v1','k2':'v2'}#添加
dic.setdefault('k2','999')
print(dic)
#设置:添加,修改,第二种方法
dic['k2'] = 999{'k1': 'v1', 'k2': 'v2'}
(5)update() 更新字典中的值
dic = {'k1':'v1','k2':'v2'} # dict类的一个对象dic.update({'k4':'v4','k2':'v5'})
print(dic)'k1': 'v1', 'k2': 'v5', 'k4': 'v4'}
(6)fromkeys() 生成一个字典,不同的key中指向同一个地址
val = dict.fromkeys(['k1','k2','k3'],666)print(val)
val['k1'] = 999
print(val)
val = dict.fromkeys(['k1','k2','k3'],[])
val['k1'].append(678)
val['k2'].append(999)
print(val)
val = dict.fromkeys(['k1','k2','k3'],[])
val['k1'].append(666)
val['k1'] = [1,2,3]
print(val){'k1': 666, 'k2': 666, 'k3': 666}
{'k1': 999, 'k2': 666, 'k3': 666}
{'k1': [678, 999], 'k2': [678, 999], 'k3': [678, 999]}
{'k1': [1, 2, 3], 'k2': [666], 'k3': [666]}