【发布时间】:2021-10-20 15:21:10
【问题描述】:
我有一个格式如下的文件:
name x y clas
x1 1 1 A
x2 2 2 B
x3 3 3 B
x4 4 4 C
x5 5 5 D
并且正在尝试创建一个以clas 作为键的字典,并基于它创建name 组:
#Just reading reading the file in
data = {}
with open('sample.csv') as file:
next(file)
reads = file.readlines()
for lines in reads:
line = lines.strip('\n').lower()
(name, x, y, clas) = line.split(",")
data[name] = x,y,clas
#How to assign "array" values based on their "clas"
dictionary = {}
array = ['x1', 'x2', 'x3', 'x4', 'x5']
for i in range(len(array)):
classs = data.get(array[i])[2]
dictionary[classs] = [array[i]]
print(dictionary)
该函数应该输出一个字典,其中“clas”作为键,对应的“name”值。
但目前的输出是{'a': ['x1'], 'b': ['x3'], 'c': ['x4'], 'd': ['x5']},其中包含具有相同键的“名称”值。
不知道要写什么条件才能正确输出字典,那么有没有办法让输出成为{'a': ['x1'], 'b': ['x2','x3'], 'c': ['x4'], 'd': ['x5']}只有默认的python函数?...
【问题讨论】:
-
您只是每次都覆盖上一个密钥:
dictionary[classs] = [array[i]]...想想您将如何处理这个...检查密钥是否已经存在,如果不存在,请使用与上面相同的分配,如果是,追加到已经存在的列表 -
顺便说一句,停止迭代
range(len(array)),直接迭代array
标签: python python-3.x dictionary