1. 字典
1.1 字典的创建
字典是另一种可变容器模型,且可存储任意类型对象。
字典的每个键值(key=>value)对用冒号(:)分割,每个对之间用逗号(,)分割,整个字典包括在花括号(**{})**中 ,格式如下所示:
d = {key1 : value1, key2 : value2 }
键必须是唯一的,但值则不必。
也可以使用dict()来创建字典:
例如:
print(dict(name='dong',age='29'))
运行结果
{‘name’: ‘dong’, ‘age’: ‘29’}
1.2 字典元素的读取:
a_dict = {"key1": "a", "key2": "b"}
print(a_dict["key1"])
print(a_dict["key2"])
运行结果:
a
b
a_dict = {"key1": "a", "key2": "b"}
print(a_dict["key1"])
print(a_dict["key2"])
print(a_dict["key3"])
键值不存在是会抛出异常
a
Traceback (most recent call last):
b
File “F:/python/pythonbase/base/dict/text.py”, line 4, in
print(a_dict[“key3”])
KeyError: ‘key3’
使用字典对象get()方法获取键对应的值,键不存在时返回None
print(a_dict.get('key1'))
print(a_dict.get("key3"))
运行结果:
a
None
使用字典对象的items()方法可以返回字典的键、值对列表
a_dict = {"key1": "a", "key2": "b"}
for item in a_dict.items():
print(item)
运行结果
(‘key1’, ‘a’)
(‘key2’, ‘b’)
a_dict = {"key1": "a", "key2": "b"}
for item in a_dict:
print(item)
不加特殊说明,默认输出键
key1
key2
使用字典对象的keys()方法可以返回字典的键列表
a_dict = {"key1": "a", "key2": "b"}
for item in a_dict.keys():
print(item)
运行结果:
key1
key2
使用字典对象values()方法可以返回字典的值列表
a_dict = {"key1": "a", "key2": "b"}
for item in a_dict.values():
print(item)
运行结果:
a
b
使用字典对象的setdefault()方法返回指定"键"对应的值,如果字典中不存在"键素并设置该"键"对应的"值",不能更改键值
a_dict = {"key1": "a", "key2": "b"}
print(a_dict.setdefault('key1'))
print(a_dict.setdefault('key3','c'))
print(a_dict)
运行结果
a
c
{‘key1’: ‘a’, ‘key2’: ‘b’, ‘key3’: ‘c’}
1.3字典元素的添加
以指定键为下标为字典赋值时,若键存在,则可也修改该键值,若不存在,则表示添加一个键、值对。
例如:
a_dict = {"key1": "a", "key2": "b"}
a_dict["key3"] = 'c' #添加一个新的元素
print(a_dict)
运行结果:
{‘key1’: ‘a’, ‘key2’: ‘b’, ‘key3’: ‘c’}
使用字典对象的update方法将另一个字典的键、值对添加到当前字典对象
a_dict = {"key1": "a", "key2": "b"}
a_dict.update({'a':'a'})#添加新的键值对
print(a_dict)
运行结果:
{‘key1’: ‘a’, ‘key2’: ‘b’, ‘a’: ‘a’}
1.4字典删除
使用del删除整个字典,或者字典中指定元素
使用pop()和popitem()方法弹出并删除指定元素
使用clear()方法清空字典中所有元素
字典clear()方法
a_dict = {"key1": "a", "key2": "b"}
a_dict.clear()
print(a_dict)
反回一个空字典:
{}
字典pop()方法:
移出字典数据pop()方法的作用是,删除指定给定键所对应的值,返回这个值并从字典中把它移出。注意字典pop()方法与列表pop方法作用完全不同。
a_dict = {"key1": "a", "key2": "b"}
a_dict.pop('key2')
print(a_dict)
运行结果:
{‘key1’: ‘a’}
1.5.判断一个key是否在字典中:
使用in方法:
a_dict = {"key1": "a", "key2": "b"}
#打印返回值,其中a_dict.keys是列出字典所有的key
print('key2' in a_dict)
print('key2' in a_dict.keys())
#两个的结果都是返回Ture
运行结果:
True
True
1.6.遍历字典
遍历key值
a_dict = {"key1": "a", "key2": "b"}
for key in a_dict:
print(key + ":"+a_dict[key])
key1:a
key2:b
for key in a_dict.keys():
print(key+ ":"+ a_dict[key])
key1:a
key2:b
上面两种方法完全等价。
遍历value值:
a_dict = {"key1": "a", "key2": "b"}
for key in a_dict.values():
print(key)
运行结果:输出键值
a
b
遍历字典项:
a_dict = {"key1": "a", "key2": "b"}
for key in a_dict.items():
print(key)
(‘key1’, ‘a’)
(‘key2’, ‘b’)
遍历字典键值:
a_dict = {"key1": "a", "key2": "b"}
#key:键 value:键值
for key,value in a_dict.items():
print(key+":"+value)
key1:a
key2:b