Python Splitting一个String为字典创建几个键

时间:2016-04-09 23:22:57

标签: python list function dictionary key

所以我正在尝试编写一个函数来读取文本文件,从一行文本中提取所需的信息,然后将该信息分配给python字典中的键。但是这里有一个问题。

def read_star_names(filename):
"""
Given the name of a file containing a star catalog in CSV format, produces a dictionary 
where the keys are the names of the stars and the values are Henry Draper numbers as integers.

If a star has more than one name, each name will appear as a key 
in the dictionary. If a star does not have a name it will not be 
represented in this dictionary.

example return: {456: 'BETA', 123: 'ALPHA', 789: 'GAMMA;LITTLE STAR'}
"""
result_name = {}
starfile = open(filename, 'r')
for dataline in starfile:
    items = dataline.strip().split(',')
    draper = int(items[3])
    name = str(items[6])
    result_name[name] = draper
starfile.close()
return result_name

这是试图读这个:

0.35,0.45,0,123,2.01,100,ALPHA

-0.15,0.25,0,456,3.2,101,BETA

0.25,-0.1,0,789,4.3,102,GAMMA; LITTLE STAR

我遇到的问题是它返回的是: {'ALPHA':123,'GAMMA; LITTLE STAR':789,'BETA':456}

我希望GAMMA和LITTLE STAR是单独的键,但仍然引用相同的数字,789。

我该怎么办? 我尝试用分号分割文本行,但后来添加了索引,我很难管理它们。

感谢。

1 个答案:

答案 0 :(得分:0)

您已经隔离了包含所有名称的部分,您需要做的就是将名称分开并为每个名称分别创建单独的键,因此

 for i in name.split(";"):
        result_name[i] = draper
相关问题