字典

Python内置的数据结构之一,与列表一样是一个可变序列
# 以键值对方式存储数据,无序序列
students = {
    'a': 100,
    'b': 90,
    'c': 75
}
  • students: 字典名;
  • 冒号前为键key,后为值value。
  • 根据key查找value位置,通过hash(key)计算;hash(key)为不可变序列(不支持增删改,如字符串和数字)

字典的特点

  1. 所有元素都是键值对,key不可重复,value无限制
  2. 字典中元素是无序的
  3. key必须是不可变对象(如字符串、数字)
  4. 可动态的伸缩
  5. 浪费较大的内存,查询速度快,使用空间换时间的数据结构

创建方式

# 1.使用{}
s = {'1': 1, '2': 2, '3': 3}
# 2.使用内置函数
x = dict(name='1', age=22)
# 空字典
y = {}

字典的常用操作

# 1.获取字典中的元素,使用[]/get()
print(s['1'])  # 1
# print(s['11'])  # key不存在时,抛出KeyError: '11'

print(s.get('2'))  # 2
print(s.get('22'))  # key不存在时,输出None
print(s.get('22', 222))  # key不存在时,222为提供的默认值,结果输出222

# 2.判断key是否存在在字典中,in/not in
x1 = dict(name='1', age=22)
print('name' in x1)  # True
print('name' not in x1)  # False

# 3.删除字典中指定的键值对
del x1['name']

# 4.清空字典
x1.clear()

# 5.增加键值对
x1['333'] = 222
print(x1)  # {'333': 222}

# 6.修改键值对
x1['333'] = 333
print(x1)  # {'333': 333}

字典的视图操作

# 1.keys(): 获取字典所有的key
s1 = {'1': 1, '2': 2, '3': 3}
print(s1.keys())  # dict_keys(['1', '2', '3'])
print(list(s1.keys()))  # ['1', '2', '3'];将key的视图转成列表
# 2.values(): 获取字典所有的values
print(s1.values())  # dict_values([1, 2, 3])
print(list(s1.values()))  # [1, 2, 3];将values的视图转成列表
# 3.items(): 获取字典所有的键值对
print(s1.items())  # dict_items([('1', 1), ('2', 2), ('3', 3)])
print(list(s1.items()))  # [('1', 1), ('2', 2), ('3', 3)];将items的视图转成列表,由元组组成

字典元素的遍历

s2 = {'one': 1, 'two': 2, 'three': 3}
for item in s2:
    print(item)

字典生成式

使用内置函数zip(): 将对象中对应的元素打包成一个元组,返回由这些元组组成的列表
a = ['张三', '李四', '王五']
b = [21, 22, 23]
print(list(zip(a, b)))  # [('张三', 21), ('李四', 22), ('王五', 23)]
# 语法: {key.upper():value for key,value in zip(keys, values)}
print({key.upper(): value for key, value in zip(a, b)})  # {'张三': 21, '李四': 22, '王五': 23}

泡琳
0 声望0 粉丝

慢慢成长吧