在Python语言中,Dictionary是一种非常有用的数据类型,尤其是在数据存储和检索方面。Dictionary是一种以键值对形式存储数据的数据结构,它支持快速的检索和插入、删除操作。本文将从多个方面对Python Dictionary做详细的阐述。
一、 Dictionary的基本操作
1)创建Dictionary
dict1 = {'name': 'Bob', 'age': 20, 'gender': 'male'}
2)访问Dictionary元素
print(dict1['name'])
3)更新Dictionary元素
dict1['age'] = 21
4)删除Dictionary元素
del dict1['gender']
5)遍历Dictionary
for key, value in dict1.items():
print(key, value)
二、 Dictionary的常见应用
1. 计数
可以利用Dictionary进行统计一个序列中各个元素出现的次数。
words = ['apple', 'banana', 'apple', 'orange', 'banana', 'banana']
word_count = {}
for word in words:
if word in word_count:
word_count[word] += 1
else:
word_count[word] = 1
print(word_count)
2. 缓存
Dictionary可以用来存储经常使用的计算值,以避免重复计算。
cache_dict = {}
def complex_calculation(n):
if n in cache_dict:
print("Cache hit!")
return cache_dict[n]
else:
print("Cache miss")
result = # do some complex calculation
cache_dict[n] = result
return result
3. 分组
可以利用Dictionary将一组数据按照指定规则进行分组。
data = [
{'name': 'Bob', 'age': 20, 'gender': 'male'},
{'name': 'Alice', 'age': 21, 'gender': 'female'},
{'name': 'Charlie', 'age': 22, 'gender': 'male'},
{'name': 'David', 'age': 23, 'gender': 'male'},
{'name': 'Eve', 'age': 24, 'gender': 'female'}
]
group_dict = {}
for d in data:
if d['gender'] in group_dict:
group_dict[d['gender']].append(d)
else:
group_dict[d['gender']] = [d]
print(group_dict)
三、 使用Dictionary解决实际问题的例子
1. 统计词频
假设有一篇文章,需要计算其中每个单词出现的次数。
with open('article.txt', 'r') as f:
words = f.read().split()
word_count = {}
for word in words:
if word in word_count:
word_count[word] += 1
else:
word_count[word] = 1
2. 统计电影票房
假设有一组电影信息数据,包括电影名称和票房,需要根据电影名称将票房进行统计。
movie_data = [
{'name': 'Avatar', 'box_office': 2784},
{'name': 'Titanic', 'box_office': 2187},
{'name': 'Star Wars: The Force Awakens', 'box_office': 2068},
{'name': 'Avengers: Endgame', 'box_office': 2797},
{'name': 'Avatar', 'box_office': 2746},
{'name': 'The Lion King', 'box_office': 1657},
{'name': 'The Avengers', 'box_office': 1519}
]
box_office_dict = {}
for movie in movie_data:
if movie['name'] in box_office_dict:
box_office_dict[movie['name']] += movie['box_office']
else:
box_office_dict[movie['name']] = movie['box_office']
3. 基于Dictionary实现用户系统
假设需要实现一个简单的用户系统,包括注册、登录和退出登录等功能。
users = {}
def register():
username = input("请输入用户名:")
password = input("请输入密码:")
if username in users:
print("该用户名已被注册")
else:
users[username] = password
print("注册成功")
def login():
username = input("请输入用户名:")
password = input("请输入密码:")
if username in users and users[username] == password:
print("登录成功")
else:
print("用户名或密码错误")
def logout():
print("退出登录")
while True:
choice = input("请选择操作:1. 注册,2. 登录,3. 退出登录")
if choice == '1':
register()
elif choice == '2':
login()
elif choice == '3':
logout()
break
原创文章,作者:小蓝,如若转载,请注明出处:https://www.506064.com/n/159359.html
微信扫一扫
支付宝扫一扫