Python序列之字典

本文介绍了Python中的字典,其作为无序对象集合,通过键而非索引访问。字典是可变的,允许嵌套,键必须唯一且不可变。内容包括创建和删除字典、键值对访问、遍历、添加、修改和删除元素,以及字典推导式的使用。

Python中的字典相当于Java中的Map对象
字典的特征:

  • 通过键而不是通过索引来读取
  • 字典是任意对象的无序集合
  • 字典是可变的,并且可以任意嵌套
  • 字典中的键必须唯一
    键出现两次,则后一个值会被记住
  • 字典中的键必须不可变
    键可以使用数字、字符串、元组,不能使用列表

创建和删除

dictionary = {'qq': '61553696', '博客': '听障老男孩', '电话': '8888888'}
print(dictionary)

"""两种方法创建空字典"""
dictionary = {}
dictionary1 = dict()

"""已有数据创建字典"""
# 1、映射函数创建字典
name = ['张三', '李四', '王五']
age = ['19', '18', '17']
# zip()函数 将多个列表或元组对应位置的元素组合为元组, 返回这些内容的zip对象
dictionary = dict(zip(name, age))
print(dictionary)

# 2、键-值对 创建字典
dictionary = dict(qq='61553696', 博客='听障老男孩', 电话='8888888')
print(dictionary)

# 元组和列表创建字典
name_tuple = ('张三', '李四', '王五')
age = ['19', '18', '17']

dict1 = {name_tuple: age}
print(dict1)    # 结果为:  {('张三', '李四', '王五'): ['19', '18', '17']}

# 清除字典的全部元素, 源字典变为空字典
dict1.clear()
print(dict1)    # {}

# del命令 删除整个字典
del dict1
print(dict1)    # NameError: name 'dict1' is not defined

# pop()方法 删除并返回指定 ‘键’的元素
# popitem()方法 删除并返回字典中的一个元素

键值对访问字典

# 获取指定键的值时, 如果指定的键不存在,就会抛出异常
dictionary = {'张三': 18,  '李四': 19, '王五': 20}
# print(dictionary['赵六']) # KeyError: '赵六'

# 解决方法一:使用if语句
print(dictionary['赵六'] if '赵六' in dictionary else '字典没有此人')

# 解决方法二: get()方法 指定的键 不存在 返回一个默认值
print(dictionary.get('赵六')) # None
print(dictionary.get('赵六', '字典没有此人'))

遍历字典

# items()方法  获取 '键-值对' 元组列表
dictionary = {'张三': 18,  '李四': 19, '王五': 20}
for item in dictionary.items():
    print(item)

"""
输出结果:
('张三', 18)
('李四', 19)
('王五', 20)
"""

# 获取每个键和值
for key,value in dictionary.items():
    print(key, value)

"""
输出结果:
张三 18
李四 19
王五 20
"""

# values() 返回字典的‘值’ 列表
print(dictionary.values())  # dict_values([18, 19, 20])
for value in dictionary.values():
    print(value)

# keys() 返回字典的 '键' 列表
print(dictionary.keys())    # dict_keys(['张三', '李四', '王五'])
for key in dictionary.keys():
    print(key)

添加、修改和删除字典元素

# 添加
dictionary = dict((('张三', 18), ('李四', 20), ('王五', 33)))
dictionary['赵六'] = 29
print(dictionary)  # {'张三': 18, '李四': 20, '王五': 33, '赵六': 29}

# 修改
dictionary['李四'] = 100
print(dictionary)   # {'张三': 18, '李四': 100, '王五': 33, '赵六': 29}


# 删除 del
del dictionary['李四']
print(dictionary)   # {'张三': 18, '王五': 33, '赵六': 29}

# del dictionary['haha']  # 删除不存在的键抛出的异常 KeyError: 'haha'
# 解决
if 'haha' in dictionary:
    del dictionary['哈哈']
print(dictionary)

字典推导式

  • 快速生成一个字典, 和列表推导式类似
# 生成4个随机数的字典, 其中字典的键使用数字表示
import random

randomdict = {i:random.randint(10, 100) for i in range(1, 5)}
print('生成的字典为: ', randomdict)

# 列表生成 字典
name = ['张三', '李四', '王五']
age = [18, 19, 20]
dictionary = {i: j for i, j in zip(name, age)}
print(dictionary)```

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值