[英]How to read from a text file and store multiple values to a key in dictionary
My text file is of the form: 我的文本文件的格式为:
ABC,_XYZ 45.1976844 -69.458819
AWA,_WES 44.946356 -90.315969
AXA,_WWA 36.3055851 -104.2588701
How do I store this in a dictionary with the letters including ',' and '_' are the keys and the numbers are two different values of that key. 如何将其存储在字典中,其中包含“,”和“ _”的字母是键,而数字是该键的两个不同值。
dicta = dict()
with open("yourfile.txt", "r") as file:
for i in file:
line, *lines = i.split()
dicta[line] = lines
.split() will only split it at the spaces .split()只会在空格处分割它
the dict look like this 字典看起来像这样
{'ABC,_XYZ': ['45.1976844', '-69.458819'],
'AWA,_WES': ['44.946356', '-90.315969'],
'AXA,_WWA': ['36.3055851', '-104.2588701']}
here line takes the first value and *lines just takes the rest 这里line取第一个值,而* lines取其余值
UPDATE 更新
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))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.