dict类型是字典,称键值对列表,用花括号{}括起来,元素用逗号隔开。
☑语法:{"key1":value1,.....}.
☑hash算法:根据key来计算出⼀个内存地址. 然后将key-value保存在这个地址中.
☑key必须是可hash类型,理解为不可改变,value类型随意。
☑可hash类型:int/str/tuple/bool;不可hash类型:list/dict/set(集合)。
car = { 'brand': 'Ford',
'model': 'Mustang',
'year': 1964
}
上面是字典的定义,car字典包含了自己的键值对内容。
以下为:增删改查操作(内置函数)
👉查询 -⽤key作为下标来查找对应的value值. / get()
dict1 = { "name": 'hassgy', "age": 20, "job": 'doctor'}
# 通过下标查询key的value,如果没有返回None
print(dict1['name'])
print(dict1['age'])
print(dict1['job'])
-------------------------------------------------------
car = { 'brand': 'Ford', 'model': 'Mustang', 'year': 1964}
# 返回一个key的value值,如果没有第二个参数,返回默认值
x = car.get('price', 15000)
print(x)
👉增加 直接法 / setdefault()
car = { 'brand': 'Ford', 'model': 'Mustang', 'year': 1964}
# 如果car中没有这个‘price’key,直接新增该键值对。
car['price'] = 2650000
print(car)
# 第二种增加方法
x = car.setdefault('color', 'white')
print(x)
👉修改 update()
car = { 'brand': 'Ford', 'model': 'Mustang', 'year': 1964}
car.update({'color': 'White'})
print(car)
👉删除 pop() / popitem() / clear()
car = { 'brand': 'Ford', 'model': 'Mustang', 'year': 1964}
# 删掉最后一个(出栈)
car.pop('model')
print(car)
# 随机删除
car.popitem()
print(car)
# 清空car字典
car.clear()
print(car)
其他内置函数操作
# 构建新字典
x = dict(name = 'John', age = 36, country = 'Norway')
print(x)
#构建空值的键值对字典的方法
x = ('key1', 'key2', 'key3')
thisdict = dict.fromkeys(x)
print(thisdict)
--------------------------------------------------------------
{'key1': None, 'key2': None, 'key3': None}
--------------------------------------------------------------
# 浅拷贝(后续会详细讲,还有深拷贝)
car = { 'brand': 'Ford', 'model': 'Mustang', 'year': 1964}
x = car.copy()
print(x)
# 返回一个list列表,里面是tuple元组
x = car.items()
car['year'] = 2018
print(x)
----------------------------------------------------------------------
dict_items([('brand', 'Ford'), ('model', 'Mustang'), ('year', 2018)])
----------------------------------------------------------------------
# 返回一个key列表list
x = car.keys()
car['color'] = 'white'
print(x)
#返回一个value列表list
x = car.values()
car['year'] = 2018
print(x)
字典之间嵌套使用
car = { 'brand': 'Ford',
'model': 'Mustang',
'year': 1964,
'car_class': {
'brand': 'Hass',
'model': 'huya',
'year': 1245
},
'children': ['child1', 'child2'],
'desc': 'He does not like you!!!'
}
字典里面又嵌套字典,只要key是可hash类型即可,value任何类型数据都可以。
print(car.get('year'))
# value是一个字典,接着用字典的函数进行操作
print(car.get('car_class').get('model'))
# value是一个列表,接着用列表函数进行操作
print(car.get(chidren)[1])
最后就是集合,下次更新~
代码素材采摘VS code自带例子。
网友评论