文章目录
#字典作用:存多个值,key-value存取,取值速度快
定义:key必须是不可变类型,value可以是任意类型
info1={'name':'egon',
'age':18,
'sex':'male',
'a':{2:'d',
'ad':('d'),
(54):[12,434,56]}
} #本质info=dict({....})
print(info1)
#或
info2=dict(name='egon',
age=18,
sex='male')
print(info2)
#或
info3=dict([['name','egon'],('age',18)])
print(info3)
#或
{}.fromkeys(('name','age','sex'),None)
{‘name’: ‘egon’, ‘age’: 18, ‘sex’: ‘male’, ‘a’: {2: ‘d’, ‘ad’: ‘d’, 54: [12, 434, 56]}}
{‘name’: ‘egon’, ‘age’: 18, ‘sex’: ‘male’}
{‘name’: ‘egon’, ‘age’: 18}
{‘age’: None, ‘name’: None, ‘sex’: None}
{}.fromkeys(('name','age','sex'),(1,2,3))
{‘age’: (1, 2, 3), ‘name’: (1, 2, 3), ‘sex’: (1, 2, 3)}
操作
1.按key存取value:
a = info1['age']
print(a)
b = info1['a'][54][1]
print(b)
18
434
2.长度len
print(len(info1))
print(len(info2))
print(len(info3))
4
3
2
3.成员运算in和 not in(针对keys)
print('ses' in info1)
print('sex' in info1)
False
True
4.删除
del删除
print(info1)
del info1['a'][54][1]
print('del 删除:',info1)
{‘name’: ‘egon’, ‘age’: 18, ‘sex’: ‘male’, ‘a’: {2: ‘d’, ‘ad’: ‘d’, 54: [12, 434, 56]}}
del 删除: {‘name’: ‘egon’, ‘age’: 18, ‘sex’: ‘male’, ‘a’: {2: ‘d’, ‘ad’: ‘d’, 54: [12, 56]}}
.pop()删除
info1.pop('e','18888')#“k[,d]”表示当需要删除的键不存在的时候,返回'18888'
print(info1)
info1.pop('name','18888')
print('.pop()删除:',info1)
{‘name’: ‘egon’, ‘age’: 18, ‘sex’: ‘male’, ‘a’: {2: ‘d’, ‘ad’: ‘d’, 54: [12, 56]}}
.pop()删除: {‘age’: 18, ‘sex’: ‘male’, ‘a’: {2: ‘d’, ‘ad’: ‘d’, 54: [12, 56]}}
5.键keys(),值values(),键值对items()
#字典特有的方法
print(info1.__dir__())
[‘repr’, ‘hash’, ‘getattribute’, ‘lt’, ‘le’, ‘eq’, ‘ne’, ‘gt’, ‘ge’, ‘iter’, ‘init’, ‘len’, ‘getitem’, ‘setitem’, ‘delitem’, ‘contains’, ‘new’, ‘sizeof’, ‘get’, ‘setdefault’, ‘pop’, ‘popitem’, ‘keys’, ‘items’, ‘values’, ‘update’, ‘fromkeys’, ‘clear’, ‘copy’, ‘doc’, ‘str’, ‘setattr’, ‘delattr’, ‘reduce_ex’, ‘reduce’, ‘subclasshook’, ‘init_subclass’, ‘format’, ‘dir’, ‘class’]
6.循环
for items in info1:
print(items)
age
sex
a
k1
7.更新update
print('未更新前:',info1)#未更新前
info1.update(k1=123, sex= 'female')
print('更新过后:', info1)
未更新前: {‘age’: 18, ‘sex’: ‘male’, ‘a’: {2: ‘d’, ‘ad’: ‘d’, 54: [12, 56]}}
更新过后: {‘age’: 18, ‘sex’: ‘female’, ‘a’: {2: ‘d’, ‘ad’: ‘d’, 54: [12, 56]}, ‘k1’: 123}
8.字典形式传值: “**”+字典,传值
template = "I am {name}, age:{age}"
#可以用.format()形式传入
v = template.format(**{'name':'abc','age':19})
print(v)
I am abc, age:19