1. 字典的基本性质:
- 使用{ }花括号表示;
- 关键字: dict;
- 保存的元素:键-值对(key-value);
- 空字典的两种表示方法:
dict1 = {}
dict1 = dict()
- 有内容的字典定义:
dict3 = {'ID':'110110229','name':'lily'}
dict4 = dict([('name','lucky'),('age','18')])
2. 字典的添加
空字典的定义,字典的添加,添加时若有同名的key,会出现value的值覆盖;key是唯一的,value值是可以重复的。
dict1 = {}
dict1['brand'] = 'huawei'
print(dict1)
{'brand': 'huawei'}
3. 字典的取值操作
字典的查找使用key进行value的获取。
dict1 = {}
dict1['brand'] = 'huawei'
dict1['name'] = 'tom'
print(dict1)
print(dict1['name'])
{'brand': 'huawei', 'name': 'tom'}
tom
4. 字典中items()的使用方法
item()方法把字典中每对key和value组成一个元组,并把这些元组放在列表中返回。
dict1 = {'name':'tom','age':18}
for i in dict1:
print(i)
print(dict1.items())
for key,value in dict1.items():# 遍历拿出来的是元组
print(key,value)
if value == 18:
print(key)
age
dict_items([('name', 'tom'), ('age', 18)])
name tom
age 18
age
4. 字典中的值获取
- 1 使用keys()和 values()获取字典的值
dict1 = {'name':'tom','age':18}
result1 = dict1.keys()
result = dict1.values()
print(result1)
print(result)
输出结果
print(result1)
print(result)
4.2 dict.get(key, default=None) key表示字典中要查找的键,default表示如果指定键的值不存在时,返回该默认值。
dict1 = {'name':'tom','age':18}
#dict.get(key, default=None) key表示字典中要查找的键,default表示如果指定键的值不存在时,返回该默认值。
result = dict1.get('gender','girl')
print(result)
输出结果:
girl
5. 字典的删除
根据key值来进行索引
dict1 = {'name':'tom','age':18}
print(dict1)
del dict1['name']
print(dict1)
输出:
{'name': 'tom', 'age': 18}
{'age': 18}
pop()
dict1 = {'name':'tom','age':18}
print(dict1)
result = dict1.pop('name')
print(result)
print(dict1)
返回:
{'name': 'tom', 'age': 18}
tom
{'age': 18}
popitem():
dict1 = {'name':'tom','age':18,'33':'ww','ert':'ttr'}
print(dict1)
# result = dict1.pop('name')
# print(result)
# print(dict1)
result = dict1.popitem()
print(result)
print(dict1)
result1 = dict1.popitem()
print(result1)
print(dict1)
输出:
{'name': 'tom', 'age': 18, '33': 'ww', 'ert': 'ttr'}
('ert', 'ttr')
{'name': 'tom', 'age': 18, '33': 'ww'}
('33', 'ww')
{'name': 'tom', 'age': 18}
字典的合并updata()
把字典1加到字典2上。
dict1 = {'name':'tom','age':18,'33':'ww','ert':'ttr'}
dict2 = {'2r':'54','fed':'feww'}
print(dict1)
dict2.update(dict1)
print(dict1)
print(dict2)
输出:
{'name': 'tom', 'age': 18, '33': 'ww', 'ert': 'ttr'}
{'name': 'tom', 'age': 18, '33': 'ww', 'ert': 'ttr'}
{'2r': '54', 'fed': 'feww', 'name': 'tom', 'age': 18, '33': 'ww', 'ert': 'ttr'}