1.fromkeys()根据序列,创建字典,并指定统一的值
v = dict.fromkeys(["k1",123,"999"],123)#fromkeys()根据序列,创建字典,并指定统一的值
print(v)

zip 字典 python python123字典_zip 字典 python

2.根据key获取值,当key不存在时,可以指定默认值(None)

dic = {
    'k1':'v1',
    'k2':'v2'
    }
# v = dic['k1']
# print(v)
# v = dic.get('k1',111)#.get(shef,k)方法,当要取的k不存在时,又没有指定的值显示,则显示None;
# #如果指定了不存key时显示的值时,就会显示指定的值,而不会报错;
# print(v)
v = dic.get('k11')#当key不存在时,显示默认值none;
print(v)

 

zip 字典 python python123字典_获取值_02

3.删除并获取值

# 3. 删除并获取值
dic = {
    'k1':'v1',
    'k2':'v2'
    }
# v = dic.pop('k1')
# print(dic,v)
k,v = dic.popitem()#随机删除,并取到删除后的值;
print(dic,k,v)# k,v 取删除的值对应的key, value

zip 字典 python python123字典_获取值_03

4.设置值

#当key存在时,不设置,获取当前key对应的值
#当key不存在时,设置新key以及value, 获取当前key对应的值
dic = {
    'k1':'v1',
    'k2':'v2'
    }
# v = dic.setdefault('k1',123)#1.当key存在时,不设置,获取当前key对应的值
# print(dic,v)
v = dic.setdefault('k111',123)#2.当key不存在时,设置新key以及value, 获取当前key对应的值
print(dic,v)

 结果1:

zip 字典 python python123字典_zip 字典 python_04

 

结果2:

zip 字典 python python123字典_获取值_05

 5.更新

dic = {
    'k1':'v1',
    'k2':'v2'
    }
dic.update({'k1':'1111','k3':2222}) #方式一,使用字典直接进行更新
print(dic)
dic.update(k1=123,k2=345,k3=567,k5="adsadasd")# 方式二,使用方法中e=None
print(dic)

 方式一结果:

zip 字典 python python123字典_zip 字典 python_06

方式二结果:

zip 字典 python python123字典_获取值_07

 

dic = {
    'k1':'v1',
    'k2':'v2'
    }
# v = dic.keys()#取key方法
# print(v)

# v = dic.values()#取value方法
# print(v)
# v = dic.items()#遍历key和value
# print(v)

zip 字典 python python123字典_获取值_08