练习1:列表转换为字典
编写一个 Python 程序将两个列表转换为字典,其中 list1 中的项是键,list2 中的项是值。
例:
list1 = ['Ten', 'Twenty', 'Thirty']
list2 = [10, 20, 30]
输出:
{'Ten': 10, 'Twenty': 20, 'Thirty': 30}
# 定义两个列表
list1 = ['Ten', 'Twenty', 'Thirty']
list2 = [10, 20, 30]
# 使用zip函数配对两个列表,然后转换为字典
dict_result = dict(zip(list1, list2))
# 打印结果
print(dict_result)
{'Ten': 10, 'Twenty': 20, 'Thirty': 30}
# 定义两个列表
list1 = ['Ten', 'Twenty', 'Thirty']
list2 = [10, 20, 30]
# 创建一个空字典
dict_result = {}
# 使用循环和索引来将键和值添加到字典
for i in range(len(list1)):
key = list1[i]
value = list2[i]
dict_result[key] = value
# 打印结果
print(dict_result)
{'Ten': 10, 'Twenty': 20, 'Thirty': 30}
练习2:Python 字典合并
编写一个程序,将两个字典合并为一个。
例:
dict1 = {'Ten': 10, 'Twenty': 20}
dict2 = {'Thirty': 30, 'Fourty': 40}
输出:
{'Ten': 10, 'Twenty': 20, 'Thirty': 30, 'Fourty': 40}
# 定义两个字典
dict1 = {'Ten': 10, 'Twenty': 20}
dict2 = {'Thirty': 30, 'Fourty': 40}
# 将dict2的内容更新到dict1中,这将合并两个字典
dict1.update(dict2)
# 打印合并后的字典
print(dict1)
{'Ten': 10, 'Twenty': 20, 'Thirty': 30, 'Fourty': 40}
# 定义两个字典
dict1 = {'Ten': 10, 'Twenty': 20}
dict2 = {'Thirty': 30, 'Fourty': 40}
# 使用**操作符合并字典
merged_dict = {**dict1, **dict2}
# 打印合并后的字典
print(merged_dict)
{'Ten': 10, 'Twenty': 20, 'Thirty': 30, 'Fourty': 40}
练习3:从字典中删除键值对
编写一个程序,从字典中将指定的键值对删除。
例:
dict1 = {"name": "li", "age": 25, "city": "beijing"}
key = ["age", "city"]
输出:
dict1 = {"name": "li"}
# 定义字典和要删除的键列表
dict1 = {"name": "li", "age": 25, "city": "beijing"}
keys_to_remove = ["age", "city"]
# 遍历列表,使用pop()方法删除每个键
for key in keys_to_remove:
dict1.pop(key, None) # 使用None作为pop方法的第二个参数,这样即使键不存在也不会引发错误
# 打印修改后的字典
print(dict1)
{'name': 'li'}
# 定义字典和要删除的键列表
dict1 = {"name": "li", "age": 25, "city": "beijing"}
keys_to_remove = ["age", "city"]
# 遍历列表,使用del语句删除每个键
for key in keys_to_remove:
if key in dict1: # 检查键是否存在于字典中,以避免KeyError
del dict1[key]
# 打印修改后的字典
print(dict1)
{'name': 'li'}
练习4:检查字典中的值
编写一个程序来查找字典中是否存在值 200。
例:
dict1 = {'a': 100, 'b': 200, 'c': 300}
输出:
找到指定值
# 定义字典
dict1 = {'a': 100, 'b': 200, 'c': 300}
# 检查字典中是否存在值200
if 200 in dict1.values():
print("找到指定值")
else:
print("未找到指定值")
找到指定值
练习5:对字典进行排序
提示:
import operator
dict1 = {'a': 12, 'b': 5, 'c': 23, 'd': 40}
dict2=sorted(dict1.items(),key = operator.itemgetter(1))
print(dict2)
输出结果为:[('b', 5), ('a', 12), ('c', 23), ('d', 40)]
问题:如何转化为字典?
import operator
# 原始字典
dict1 = {'a': 12, 'b': 5, 'c': 23, 'd': 40}
# 对字典的项进行排序
sorted_items = sorted(dict1.items(), key=operator.itemgetter(1))
# 将排序后的项列表转换回字典
sorted_dict = {key: value for key, value in sorted_items}
# 打印排序后的字典
print(sorted_dict)
{'b': 5, 'a': 12, 'c': 23, 'd': 40}
import operator
dict1 = {'a': 12, 'b': 5, 'c': 23, 'd': 40}
dict2 = dict(sorted(dict1.items(), key=operator.itemgetter(1)))
print(dict2)
{'b': 5, 'a': 12, 'c': 23, 'd': 40}
xm,xg去超市里购买水果。小明购买了apple,strawberry,banana,一共花了89块钱,小刚购买了grape,orange,berry,一共花了87块钱。请从上面的描述中提取数据,存储到字典中,可以根据姓名获取这个人购买的水果种类和总费用。注意:输出的信息不允许有列表,同时要求以姓名做key,value仍然是字典。
# 创建包含购买信息的字典
purchases = {
"xiaoming": {
"fruits": "apple,strawberry,banana",
"cost": 89
},
"xiaogang": {
"fruits": "grape,orange,berry",
"cost": 87
}
}
# 打印字典以验证数据结构
print(purchases)
{'xiaoming': {'fruits': 'apple,strawberry,banana', 'cost': 89}, 'xiaogang': {'fruits': 'grape,orange,berry', 'cost': 87}}
将list1中的tt修改为大写TT,并输出修改后的list1验证结果是否符合要求
list1 =[['k',['qwe',20,{'k1':['tt',3,'1']},89],'ab']]
# 定义列表
list1 = [['k',['qwe',20,{'k1':['tt',3,'1']},89],'ab']]
# 修改'k1'键对应的列表中的'tt'
list1[0][1][2]['k1'][0] = 'TT'
# 打印修改后的列表以验证结果
print(list1)
[['k', ['qwe', 20, {'k1': ['TT', 3, '1']}, 89], 'ab']]
按照要求实现以下功能: ls= [1,2,3,'a','b',4,'c'],创建一个字典dic_1,其中该字典的键k1,k2对应的值都是一个空列表,请将ls中的索引为奇数对应的元素依次追加到这个列表中,最终由这些元素构成的列表作为键k1对应的值。请将ls中的索引为偶数对应的元素依次追加到这个列表中,最终由这些元素构成的列表作为键k2对应的值。最后,输出字典验证结果是否符合预期。
# 初始列表
ls = [1,2,3,'a','b',4,'c']
# 创建字典,键k1和k2对应的值为两个空列表
dic_1 = {'k1': [], 'k2': []}
# 遍历列表,依据索引奇偶性追加到相应的列表
for index, value in enumerate(ls):
if index % 2 == 0: # 索引为偶数
dic_1['k2'].append(value)
else: # 索引为奇数
dic_1['k1'].append(value)
# 输出字典验证结果
print(dic_1)
{'k1': [2, 'a', 4], 'k2': [1, 3, 'b', 'c']}
统计分词列表words中的各个词出现的频率,使用字典表示出来(提示:分词作为键,出现的频率作为对应词的值,按照出现的频率从低到高排序)
words=['i','am','a','teacher','he','is','also','a','teacher']
建立排除词库列表excludes如下:excludes = ['am', 'a'],把刚才得到的分词统计字典中在排除词库列表中的词删掉
对刚才得到的分词统计字典排序(按照出现的频率从低到高排序)
import operator
words = ['i', 'am', 'a', 'teacher', 'he', 'is', 'also', 'a', 'teacher']
excludes = ['am', 'a']
# 创建一个空字典来统计词频
word_freq = {}
# 统计每个单词出现的次数
for word in words:
word_freq[word] = word_freq.get(word, 0) + 1
# 输出字典验证结果
print(word_freq)
# 删除排除词库列表中的词
for exclude_word in excludes:
if exclude_word in word_freq:
del word_freq[exclude_word]
# 输出处理后的字典
print(word_freq)
# 使用operator模块对字典按值排序(频率从低到高)
sorted_word_freq = dict(sorted(word_freq.items(), key=operator.itemgetter(1)))
# 输出排序后的字典项列表
print(sorted_word_freq)
{'i': 1, 'am': 1, 'a': 2, 'teacher': 2, 'he': 1, 'is': 1, 'also': 1}
{'i': 1, 'teacher': 2, 'he': 1, 'is': 1, 'also': 1}
{'i': 1, 'he': 1, 'is': 1, 'also': 1, 'teacher': 2}
有字典列表如下:
stu_info = [{'name':'mary','tid':1001,'title':'操作系统'},
{'name':'mary','tid':1001,'title':'计算机网络'},
{'name':'jerry','tid':1002,'title':'操作系统'},
{'name':'jerry','tid':1002,'title':'数据结构'},
{'name':'jack','tid':1003,'title':'操作系统'},
{'name':'jack','tid':1003,'title':'计算机网络'},
{'name':'jack','tid':1003,'title':'数据结构'}]
请利用python语言编写程序对字典列表stu_info进行处理,将同一名同学的信息进行合并处理得到类似如下所示的结果:
[{'name': 'mary', 'tid': 1001, 'title': ['操作系统', '计算机网络']}, {'name': 'jerry', 'tid': 1002, 'title': ['操作系统', '数据结构']}, {'name': 'jack', 'tid': 1003, 'title': ['操作系统', '计算机网络', '数据结构']}]
stu_info = [
{'name': 'mary', 'tid': 1001, 'title': '操作系统'},
{'name': 'mary', 'tid': 1001, 'title': '计算机网络'},
{'name': 'jerry', 'tid': 1002, 'title': '操作系统'},
{'name': 'jerry', 'tid': 1002, 'title': '数据结构'},
{'name': 'jack', 'tid': 1003, 'title': '操作系统'},
{'name': 'jack', 'tid': 1003, 'title': '计算机网络'},
{'name': 'jack', 'tid': 1003, 'title': '数据结构'}
]
# 创建一个新的字典来组合信息
combined_info = {}
# 遍历原始列表,合并信息
for info in stu_info:
key = (info['name'], info['tid']) # 将名字和tid作为唯一的键
if key not in combined_info:
# 如果键不存在,创建新条目
combined_info[key] = {
'name': info['name'],
'tid': info['tid'],
'title': [info['title']]
}
else:
# 如果键存在,添加新的课程标题到标题列表
combined_info[key]['title'].append(info['title'])
# 从聚合字典中获取所有值,这些值是我们合并后的字典列表
merged_stu_info = list(combined_info.values())
# 输出合并后的列表信息
print(merged_stu_info)
[{'name': 'mary', 'tid': 1001, 'title': ['操作系统', '计算机网络']}, {'name': 'jerry', 'tid': 1002, 'title': ['操作系统', '数据结构']}, {'name': 'jack', 'tid': 1003, 'title': ['操作系统', '计算机网络', '数据结构']}]