简体   繁体   English

读取从文本文件到字典python的所有行

[英]Read all lines from a text file to dictionary python

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部分作为键,将数字作为值。

Dictionary keys must be unique. 字典键必须唯一。 You have only one unique 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 largest value, 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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM