Python数据结构:字典(dict)详解

在这里插入图片描述

1.字典概念

  字典在其他语言中可能会被称为“关联存储”或“关联数组”。
  在Python中,字典(Dictionary)是一种可变、无序且键值对(key-value pairs)唯一的数据结构。
  字典也是一种标准映射类型,mapping对象会将hashtable值映射到任意对象,映射属于可变对象。
  字典的键 几乎可以为任何不可变类型。 不是 hashable的值,即包含列表、字典或其他可变类型(按值比较而非按对象标识比较)的值不可被用作键。字符串或数字总是可以作为键。如果一个元组只包含了字符串、数字或元组则可以作为键;如果元组直接或间接的包含了任何可变对象,则不能作为键。

2.字典创建

  字典可以用多种方式进行创建,一般使用{}内用,隔开 键:值对的方式、字典推导式、dict()构造函数等。
  注意:
  如果没有给出位置参数,将创建一个空字典。
  如果给出一个位置参数并且其属于映射对象,将创建一个具有与映射对象相同键值对的字典。
  否则的话,位置参数必须为一个iterable 对象。该可迭代对象中的每一项本身必须为一个刚好包含两个元素的可迭代对象。每一项中的第一个对象将成为新字典的一个键,第二个对象将成为其对应的值。
如果一个键出现一次以上,该键的最后一个值将成为其在新字典中对应的值。
  如果给出了关键字参数,则关键字参数及其值会被加入到基于位置参数创建的字典。如果要加入的键已存在,来自关键字参数的值将替代来自位置参数的值。
my_dict = {'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}

# 创建空字典
empty_dict1 = {}
empty_dict2 = dict()

dict1 = {'one':1,'two':2,'three':4} # 输出 {'one': 1, 'two': 2, 'three': 4}
dict2 = dict(one=1,two=2,three=4) # 输出 {'one': 1, 'two': 2, 'three': 4}
dict3 = dict(zip(['one','two','three'],[3,4,5])) # 输出 {'one': 3, 'two': 4, 'three': 5}
dict4 = dict({'one':1,'two':3,'three':4}) # 输出 {'one': 1, 'two': 3, 'three': 4}
dict5 = dict({'one':2,'three':4} , two=6) # 输出 {'one': 2, 'three': 4, 'two': 6}
dict6 = dict([('two',3),('three',6),('one',8)]) # 输出 {'two': 3, 'three': 6, 'one': 8}
dict7 = {x:x**2 for x in (2,4,6)} # 输出 {2: 4, 4: 16, 6: 36}

3. 字典常用方法

  以下表格列出了字典常用的一些方法,下面通过示例进行说明。
在这里插入图片描述

3.1 keys()

  用于返回一个包含字典所有键的可迭代对象。这个可迭代对象实际上是一个视图(view),称为字典键视图(dict_keys

"""
  keys 就是一个包含字典中所有键的视图。
  字典视图是动态的,即当字典发生变化时,视图会自动更新。
  可以将该视图转换为列表或其他数据类型
"""
dict_fruits = {'fruit1':'apple','fruit2':'banana','fruit3':'pear'}
keys = dict_fruits.keys()
print(f'输出的为字典键视图:{keys}') # 输出 dict_keys(['fruit1', 'fruit2', 'fruit3'])

list_keys = list(keys) # 将字典键视图转换为列表
print(f'转换为list后的keys:{list_keys}')

3.2 values()

  用于返回一个包含字典所有值的可迭代对象。类似于 dict.keys() 返回的是一个字典键的视图,dict.values() 返回的是字典值的视图,称为字典值视图(ict_values)。

"""
  values 就是一个包含字典中所有值的视图。
  字典视图是动态的,即当字典发生变化时,视图会自动更新。
  可以将该视图转换为列表或其他数据类型
"""
dict_fruits = {'fruit1':'apple','fruit2':'banana','fruit3':'pear'}
values = dict_fruits.values()
print(f'输出的为字典值视图:{values}')

list_values = list(values) # 将字典值视图转换为列表
print(f'转换为list后的values:{list_values}')

3.3 items()

  用于返回一个包含字典所有键值对的可迭代对象。这个可迭代对象实际上是字典项视图(dict_items)。

dict_fruits = {'fruit1':'apple','fruit2':'banana','fruit3':'pear'}
items = dict_fruits.items()
print(f'输出的为字典项视图:{items}')

list_items = list(values) # 将字典项视图转换为列表
print(f'转换为list后的items:{list_items}')

# 该方法多用于遍历字典的键值对
for key,value in dict_fruits.items():
    print(f'key = {key},value = {value}')

# 判断键值对是否存在字典中
if('fruit1','apple') in dict_fruits.items():
    print(f'键值对(fruit1,apple)在 dict_fruits 中')

3.4 get(key, default=None)

  是用于获取指定键的值。如果字典中存在指定的键,则返回该键对应的值;如果字典中不存在指定的键,则返回指定的默认值。
  在不确定字典中是否包含某个键的情况下,可以避免因为键不存在而引发的异常,通过提供默认值,可以更加灵活地处理字典中的数据。

dict_fruits = {'fruit1':'apple','fruit2':'banana','fruit3':'pear'}
# 获取存在的键的值
value1 = dict_fruits.get('fruit1')
print(f'字典存在的key值:{value1}') # 输出 apple

# 获取不存在的键的值,使用默认值
value2 = dict_fruits.get('fruit00','不存在')
print(f'键的值存在情况:{value2}') # 输出 不存在

# 不提供默认值,键不存在时返回None
value3 = dict_fruits.get('fruit99')
print(f'键的值存在情况:{value3}') # 输出 None

3.5 pop(key, default=None)

  用于删除指定键并返回对应的值。如果字典中存在指定的键,则该键值对被移除,并返回该键对应的值;如果字典中不存在指定的键,则返回指定的默认值(如果提供了默认值),否则引发 KeyError 异常。

dict_fruits = {'fruit1':'apple','fruit2':'banana','fruit3':'pear'}
# 删除存在的键,并返回其值
value1 = dict_fruits.pop('fruit2')
print(f'被删除的值为:{value1}') # 输出 banana

# 删除不存在的键,返回默认值
value2 = dict_fruits.pop('fruit00','不存在')
print(f'键存在情况:{value2}') # 输出 不存在

# 删除不存在的键,不提供默认值,引发 KeyError 异常
value2 = dict_fruits.pop('fruit00') # 引发 KeyError: 'fruit00'

3.6 popitem()

  用于随机删除并返回字典中的一对键值对。在 Python 3.7 及以上的版本中,删除的是字典中的最后一对键值对。在之前的版本中,字典是无序的,所以不能确定删除的是哪一对键值对。

dict_fruits = {'fruit1':'apple','fruit2':'banana','fruit3':'pear'}
item = dict_fruits.popitem()
print(f'被删除的是最后的一对键值对:{item}')
print(f'剩下的字典为:{dict_fruits}')

3.7 update(iterable)

  用于使用可迭代对象中的键值对更新字典。这个方法会将可迭代对象中的键值对添加到字典中,如果键已经存在,则更新对应的值。

dict_fruits = {'fruit1':'苹果','fruit2':'香蕉'}
# dict_fruits_2 = {'水果3':'李子','水果4':'杏子'}
# dict_fruits.update(dict_fruits_2) 直接更新字典类型的也可以
print(dict_fruits)
dict_fruits.update([('fruit3','梨子'),('fruit4','山竹')])
print(f'添加2个键值对后的字典:{dict_fruits}')
dict_fruits.update({'fruit5':'车厘子','fruit4':'榴莲'})
print(f'键存在的更新对应的值后的字典:{dict_fruits}')

3.8 clear()

  用于清空字典,即删除字典中的所有键值对,使其变为空字典。

dict_fruits = {'fruit1':'苹果','fruit2':'香蕉'}

# 清空字典
dict_fruits.clear()
print(f'字典已被清空,变为空字典:{dict_fruits}')

3.9 len(dict)

  是一个内建函数,用于返回字典(dict)中键值对的数量,即字典的长度。

dict_fruits = {'fruit1': '苹果', 'fruit2': '香蕉', '水果3': '李子', '水果4': '杏子'}

# 获取字典的长度
dict_fruits_len = len(dict_fruits)
print(f'字典中的键值对数量:{dict_fruits_len}个')

3.10 key in dict

  是一个成员运算符,用于检查字典(dict)中是否存在指定的键。如果键存在,表达式返回True,否则返回False

dict_fruits = {'fruit1': '苹果', 'fruit2': '香蕉', '水果3': '李子', '水果4': '杏子'}
return_True = '水果3' in dict_fruits
print(f'字典中存在水果3的键:{return_True}')

return_Flase = '水果99' in dict_fruits
print(f'字典中存在水果99的键:{return_Flase}')

4. 字典的应用场景

  字典在各个应用场景中有丰富的使用,包括学生信息管理在线购物任务管理URL路由映射配置管理数据存储API请求和响应数据库查询结果用户身份验证和授权数据统计等。字典的结构可以根据实际需求进行灵活设计,适用于各种数据管理和组织的场景。

4.1 学生信息管理系统

# 学生信息管理系统
students = {
    'john_doe': {'name': 'John Doe', 'age': 20, 'grades': [90, 85, 88]},
    'jane_smith': {'name': 'Jane Smith', 'age': 22, 'grades': [95, 92, 96]}
}

# 获取学生信息
student_id = 'john_doe'
student_info = students.get(student_id, {})
print(f"Student ID: {student_id}")
print(f"Name: {student_info.get('name', 'N/A')}")
print(f"Age: {student_info.get('age', 'N/A')}")
print(f"Grades: {student_info.get('grades', 'N/A')}")

4.2 在线商店购物车

# 在线商店购物车
shopping_cart = {
    'user_id': 123,
    'items': [
        {'product_id': 1, 'name': 'Product A', 'price': 29.99, 'quantity': 2},
        {'product_id': 2, 'name': 'Product B', 'price': 39.99, 'quantity': 1}
    ],
    'total': 99.97
}

# 添加新商品到购物车
new_item = {'product_id': 3, 'name': 'Product C', 'price': 19.99, 'quantity': 3}
shopping_cart['items'].append(new_item)

# 计算新的总价
total_price = sum(item['price'] * item['quantity'] for item in shopping_cart['items'])
shopping_cart['total'] = total_price

print(shopping_cart)

4.3 任务管理系统

# 任务管理系统
tasks = {
    'task1': {'title': 'Complete report', 'status': 'In Progress', 'assignee': 'John'},
    'task2': {'title': 'Code review', 'status': 'Pending', 'assignee': 'Jane'},
    'task3': {'title': 'Testing', 'status': 'Completed', 'assignee': 'Bob'}
}

# 更新任务状态
task_id = 'task2'
tasks[task_id]['status'] = 'Completed'

# 打印更新后的任务列表
for task_id, task_info in tasks.items():
    print(f"Task ID: {task_id}")
    print(f"Title: {task_info['title']}")
    print(f"Status: {task_info['status']}")
    print(f"Assignee: {task_info['assignee']}")
    print("\n")

4.4 URL路由映射

# URL路由映射
url_mapping = {
    '/home': 'home_handler',
    '/about': 'about_handler',
    '/contact': 'contact_handler'
}

# 处理请求
requested_url = '/home'
handler = url_mapping.get(requested_url, 'default_handler')
print(f"Handling {requested_url} with {handler}")

4.5 配置管理

# 配置管理
config = {
    'database': {'host': 'localhost', 'port': 3306, 'username': 'admin', 'password': 'admin123'},
    'app': {'debug_mode': True, 'timezone': 'UTC'}
}

# 获取数据库配置
db_config = config.get('database', {})
print(f"Database Host: {db_config.get('host', 'N/A')}")
print(f"Database Port: {db_config.get('port', 'N/A')}")
print(f"Database Username: {db_config.get('username', 'N/A')}")

4.6 数据存储

# 数据存储
user_data = {
    'user1': {'name': 'John', 'email': 'john@example.com', 'age': 25},
    'user2': {'name': 'Jane', 'email': 'jane@example.com', 'age': 28}
}

# 获取用户信息
user_id = 'user1'
user_info = user_data.get(user_id, {})
print(f"User ID: {user_id}")
print(f"Name: {user_info.get('name', 'N/A')}")
print(f"Email: {user_info.get('email', 'N/A')}")
print(f"Age: {user_info.get('age', 'N/A')}")

4.7 API请求和响应

# API请求和响应
api_request = {'method': 'GET', 'url': 'https://api.example.com', 'params': {'page': 1, 'limit': 10}}
api_response = {'status': 200, 'data': {'user': 'John', 'age': 25}}

# 处理API响应
if api_response['status'] == 200:
    user_data = api_response['data']
    print(f"User: {user_data['user']}, Age: {user_data['age']}")
else:
    print(f"Error: {api_response['status']}")

4.8 数据库查询结果

# 数据库查询结果
db_result = {'id': 1, 'name': 'Product A', 'price': 29.99}

# 处理查询结果
print(f"Product ID: {db_result['id']}")
print(f"Product Name: {db_result['name']}")
print(f"Product Price: {db_result['price']}")

4.9 用户身份验证和授权

# 用户身份验证和授权
user_info = {'username': 'john_doe', 'password_hash': 'hashed_password', 'role': 'admin'}

# 身份验证
input_username = 'john_doe'
input_password = 'password123'
if input_username == user_info['username'] and input_password == 'password123':
    print("Authentication successful.")
    # 检查用户权限
    if user_info['role'] == 'admin':
        print("Admin access granted.")
    else:
        print("Regular user access granted.")
else:
    print("Authentication failed.")

4.10 数据统计

# 数据统计
data = ['apple', 'banana', 'apple', 'orange', 'banana', 'apple']

# 统计元素出现次数
count_dict = {}
for item in data:
    count_dict[item] = count_dict.get(item, 0) + 1

print(count_dict)

在这里插入图片描述

  • 15
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

snail哥

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值