下面是一个根据类别对Python操作进行分类并从文件中填充字典的示例代码:
def populate_dictionary(filename):
dictionary = {}
with open(filename, 'r') as file:
for line in file:
data = line.strip().split(',')
category = data[0]
operation = data[1]
if category not in dictionary:
dictionary[category] = []
dictionary[category].append(operation)
return dictionary
# 示例文件内容:
# category1,operation1
# category2,operation2
# category1,operation3
# category2,operation4
filename = 'example.txt'
result = populate_dictionary(filename)
print(result)
这个示例中,我们首先定义了一个populate_dictionary
函数,该函数接受一个文件名作为参数。然后,我们打开文件并逐行读取其中的内容。
对于每一行,我们使用逗号分隔符将其拆分为类别和操作。然后,我们检查字典中是否已经存在该类别的键,如果不存在则将其添加到字典中。然后,我们将操作添加到对应类别的值列表中。
最后,我们返回填充好的字典。
在这个示例中,假设文件的内容如下:
category1,operation1
category2,operation2
category1,operation3
category2,operation4
运行代码后,将打印以下输出:
{'category1': ['operation1', 'operation3'], 'category2': ['operation2', 'operation4']}
这表明字典已经按类别进行了填充。
上一篇:按类别进行分组和计数
下一篇:按类别计数记录,包括零计数。