如何从文本文件读取并将多个值存储到字典中的键

时间:2018-09-16 19:34:10

标签: python python-3.x

我的文本文件的格式为:

ABC,_XYZ 45.1976844 -69.458819
AWA,_WES 44.946356 -90.315969
AXA,_WWA 36.3055851 -104.2588701

如何将其存储在字典中,其中包含字母','和'_'为键,数字是该键的两个不同值。

1 个答案:

答案 0 :(得分:2)

dicta = dict()
with open("yourfile.txt", "r") as file:
    for i in file:
        line, *lines = i.split()
        dicta[line] = lines

.split()只会在空格处将其分割

字典看起来像这样

{'ABC,_XYZ': ['45.1976844', '-69.458819'], 
'AWA,_WES': ['44.946356', '-90.315969'], 
'AXA,_WWA': ['36.3055851', '-104.2588701']}

此处行采用第一个值,*行仅采用其余值

更新

dicta = dict()
with open("yourfile.txt", "r") as file:
    for i in file:
        line, *lines = i.split()
        if line in dicta:
            dicta[line] += lines
        else:
            dicta[line] = lines


dicta = dict()
with open("yourfile.txt", "r") as file:
    for w,i in enumerate(file):
        line, *lines = i.split()
        if line in dicta:
            dicta[w] = lines
        else:
            dicta[line] = lines

dicta = list()
with open("yourfile.txt", "r") as file:
    for w,i in enumerate(file):
        line, *lines = i.split()
        dicta.append((line,lines))