day5-字典专区

# 字典
# dict
1.fromkeys()根据序列,创建字典,并指定统一的值
v = dict.fromkeys(["k1",123,"999"],123)
print(v)
{'k1': 123, 123: 123, '999': 123}
2.get()根据Key获取值,key不存在时,可以指定默认值(None)
v = dic['k11111']
print(v)
NameError: name 'dic' is not defined  
# key值不存在时会报错

dic = {'f':'df'}
v = dic.get('k1',111111)
print(v)
111111
# 根据Key获取值,key不存在时,可以指定默认值(None)
3.pop()删除并获取值
dic = {
    "k1": 'v1',
    "k2": 'v2'
}
v = dic.pop('k1',90)
print(dic,v)
k,v = dic.popitem()
print(dic,k,v)

{'k2': 'v2'} v1
{} k2 v2
 4.setdefault()设置值
# 若值已存在,不设置,获取当前key对应的值
# 不存在,设置,获取当前key对应的值
dic = {
    "k1": 'v1',
    "k2": 'v2'
}
v = dic.setdefault('k1111','123')
print(dic,v)
{'k1': 'v1', 'k2': 'v2', 'k1111': '123'} 123
5.update()更新
dic = {
    "k1": 'v1',
    "k2": 'v2'
}
dic.update({'k1': '111111','k3': 123})
print(dic)
dic.update(k1=123,k3=345,k5="asdf")
print(dic)
{'k1': '111111', 'k2': 'v2', 'k3': 123}
{'k1': 123, 'k2': 'v2', 'k3': 345, 'k5': 'asdf'}
6 keys()获取键
7 values()获取值
8 items()获取键和值
*get update
#################################
1、基本机构
info = {
"k1": "v1", # 键值对
"k2": "v2"
}
2 字典的value可以是任何值
# info = {
#     "k1": "v1", # 键值对
#     "k2": "v2"
# }
#### 2 字典的value可以是任何值
info = {
    "k1": 18,
    "k2": True,
    "k3": [
        11,
        [],
        (),
        22,
        33,
        {
            'kk1': 'vv1',
            'kk2': 'vv2',
            'kk3': (11,22),
        }
    ],
    "k4": (11,22,33,44)
}
print(info)
{'k1': 18, 'k2': True, 'k3': [11, [], (), 22, 33, {'kk1': 'vv1', 'kk2': 'vv2', 'kk3': (11, 22)}], 'k4': (11, 22, 33, 44)}
3 布尔值(1,0)、列表、字典不能作为字典的key
4 字典无序:每次输出结果位置不同
5、索引方式找到指定元素
6 字典支持 del 删除
info = {
    "k1": 18,
    2: True,
    "k3": [
        11,
        [],
        (),
        22,
        33,
        {
            'kk1': 'vv1',
            'kk2': 'vv2',
            'kk3': (11,22),
        }
    ],
    "k4": (11,22,33,44)
}
del info['k1']

del info['k3'][5]['kk1']
print(info)
{2: True, 'k3': [11, [], (), 22, 33, {'kk2': 'vv2', 'kk3': (11, 22)}], 'k4': (11, 22, 33, 44)}
7 for循环
dict
info = {
    "k1": 18,
    2: True,
    "k3": [
        11,
        [],
        (),
        22,
        33,
        {
            'kk1': 'vv1',
            'kk2': 'vv2',
            'kk3': (11,22),
        }
    ],
    "k4": (11,22,33,44)
}
for item in info:
    print(item)

for item in info.keys():
    print(item)

for item in info.values():
    print(item)

for item in info.keys():
    print(item,info[item])

for k,v in info.items():
    print(k,v)
k1 18
2 True
k3 [11, [], (), 22, 33, {'kk1': 'vv1', 'kk2': 'vv2', 'kk3': (11, 22)}]
k4 (11, 22, 33, 44)
k1 18
2 True
k3 [11, [], (), 22, 33, {'kk1': 'vv1', 'kk2': 'vv2', 'kk3': (11, 22)}]
k4 (11, 22, 33, 44)

 



 
上一篇:Java day5【第十四章】继承案例分析


下一篇:焱飞科技实习日志 Day5