将文本文件中的所有行读取到字典 python
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18968909/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Read all lines from a text file to dictionary python
提问by GivenPie
Here I have a function that, when I read, only returns the last line. What am I doing wrong?
这里我有一个函数,当我阅读时,它只返回最后一行。我究竟做错了什么?
def read():
with open("text.txt","r") as text:
return dict(line.strip().split() for line in text)
The text file is pretty simple, two columns
文本文件很简单,两列
asd 209
asd 441
asd 811
asd 160
asd 158
I want to read all the times into a dictionary, the asd
part as the keys and the numbers as the value.
我想将所有时间读入字典,将asd
部分作为键,将数字作为值。
采纳答案by Martijn Pieters
Dictionary keys must be unique. You have only oneunique key in that file.
字典键必须是唯一的。您在该文件中只有一个唯一键。
You are in essence assigning different values to the same key, and only the last value is visible as the previous values are overwritten:
您实质上是为同一个键分配不同的值,并且只有最后一个值是可见的,因为先前的值被覆盖:
>>> d = {}
>>> d['asd'] = 209
>>> d['asd'] = 441
>>> d
{'asd': 441}
To store the largestvalue, use:
要存储的最大价值,使用方法:
def read():
res = {}
with open("text.txt","r") as text:
for line in text:
key, value = line.split()
if int(value) > res.get(key, -1):
res[key] = int(value)
return res
回答by Graeme Stuart
To append values into a list for each dictionary key you can use a defaultdict
要将值附加到每个字典键的列表中,您可以使用 defaultdict
from collections import defaultdict
def read():
result = defaultdict(list)
with open("text.txt","r") as text:
for line in text:
key, value = line.strip().split()
result[key].append(value)
return result