繁体   English   中英

使用多个键从文本文件制作python字典

[英]Making python dictionary from a text file with multiple keys

我有一个名为file.txt的文本文件,其中包含一些数字,如下所示:

1 79  8.106E-08  2.052E-08  3.837E-08
1 80 -4.766E-09  9.003E-08  4.812E-07
1 90  4.914E-08  1.563E-07  5.193E-07
2 2   9.254E-07  5.166E-06  9.723E-06
2 3   1.366E-06 -5.184E-06  7.580E-06
2 4   2.966E-06  5.979E-07  9.702E-08
2 5   5.254E-07  0.166E-02  9.723E-06
3 23  1.366E-06 -5.184E-03  7.580E-06
3 24  3.244E-03  5.239E-04  9.002E-08

我想构建一个python字典,其中每行的第一个数字是键,第二个数字始终被忽略,最后三个数字作为值放置。 但是在字典中,键不能重复,所以当我编写代码(附在问题的末尾)时,得到的是

'1' : [ '90'  '4.914E-08'  '1.563E-07'  '5.193E-07' ]
'2' : [ '5'   '5.254E-07'  '0.166E-02'  '9.723E-06' ]
'3' : [ '24'  '3.244E-03'  '5.239E-04'  '9.002E-08' ]

所有其他数字都将被删除,只有最后一行保留为值。 我需要的是将所有与键相对的数字(例如1)附加到字典中。 例如,我需要的是:

'1' : ['8.106E-08'  '2.052E-08'  '3.837E-08' '-4.766E-09'  '9.003E-08'  '4.812E-07' '4.914E-08'  '1.563E-07' '5.193E-07']

有可能在python中优雅地做到吗? 我现在拥有的代码如下:

diction = {}

with open("file.txt") as f:
    for line in f:
        pa = line.split()
        diction[pa[0]] = pa[1:]

with open('file.txt') as f:
    diction = {pa[0]: pa[1:] for pa in map(str.split, f)}

您可以使用defaultdict

from collections import defaultdict
data = defaultdict(list)
with open("file.txt", "r") as f:
    for line in f:
        line = line.split()
        data[line[0]].extend(line[2:])

尝试这个:

from collections import defaultdict


diction = defaultdict(list)

with open("file.txt") as f:
    for line in f:
        key, _, *values = line.strip().split()
        diction[key].extend(values)

print(diction)

这是针对Python 3的解决方案,因为语句a, *b = tuple1在Python 2中无效。如果使用的是Python 2,请查看@ cha0site的解决方案。

使diction中每个键的值成为列表,并在每次迭代时扩展该列表。 使用现在编写的代码,当您说diction[pa[0]] = pa[1:]时,每次按键出现时,您都会覆盖diction[pa[0]]的值,它描述了您的行为重新看到。

with open("file.txt") as f:
    for line in f:
        pa = line.split()
        try:
            diction[pa[0]].extend(pa[1:])
        except KeyError:
            diction[pa[0]] = pa[1:]

在此代码中,每个diction值都将是一个列表。 在每次迭代中,如果键存在,则将使用pa新值扩展该列表,从而为您提供每个键的所有值的列表。

要在一个非常简单的for循环中执行此操作:

with open('file.txt') as f:
    return_dict = {}
    for item_list in map(str.split, f):
        if item_list[0] not in return_dict:
            return_dict[item_list[0]] = []
        return_dict[item_list[0]].extend(item_list[1:]) 
     return return_dict

或者,如果您想在一种衬里中使用defaultdict:

from collections import defaultdict
with open('file.txt') as f:
    return_dict = defaultdict(list)

    [return_dict[item_list[0]].extend(item_list[1:]) for item_list in map(str.split, f)]

    return return_dict

暂无
暂无

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

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