简体   繁体   English

将文本文件的内容读入字典

[英]Read contents of a text file into a dictionary

The contents of my text file are as follows: 我的文本文件的内容如下:

a 0 45 124 234 53 12 34
a 90 294 32 545 190 87
a 180 89 63 84 73 63 83

How can I read the contents into a dictionary such that a0 becomes the key and the rest of them as values. 如何将内容读入字典,使a0成为键,其余内容作为值。 I would want my dictionary to look like this: 我希望我的字典看起来像这样:

{a0: [45, 124, 234, 53, 12, 34], a90: [294, 32, 545, 190, 87], a180: [89, 63, 84, 73, 63, 83]}

I have tried the conventional approach where I remove the delimiter and then store it in the dictionary as shown below 我尝试了常规方法,删除定界符,然后将其存储在字典中,如下所示

newt = {}
newt = {t[0]: t[1:] for t in data}

But here I get only a as the key 但是这里我只有a作为关键

This may help you out (it's about Christmas time after all) 这可能会帮到您(毕竟是圣诞节的时候)

d = {}
with open("dd.txt") as f:
    for line in f:
        els = line.split()
        k = ''.join(els[:2])
        d[k] = list(map(int,els[2:]))
print(d)

with an input file of 输入文件为

a 0 45 124 234 53 12 34
a 90 294 32 545 190 87
a 180 89 63 84 73 63 83

it produces 它产生

{'a90': [294, 32, 545, 190, 87],
 'a180': [89, 63, 84, 73, 63, 83],
 'a0': [45, 124, 234, 53, 12, 34]}

It essentially reads each line from the file, it then splits it into chunks ignoring whitespace. 它实质上从文件中读取每一行,然后将其拆分为大块,忽略空白。

It then uses the first two elements to compose the key and the rest to compose a list, converting each element into an integer. 然后,它使用前两个元素组成键,其余部分使用组成列表,将每个元素转换为整数。

I have assumed you want the numbers as integers. 我假设您希望数字为整数。 If you want them as strings you can ignore the conversion to int 如果希望它们作为字符串,则可以忽略到int的转换。

d[k] = els[2:]

If you like one-liners (kind-of): 如果您喜欢单线(同类):

with open('my_file.txt') as f:
    res = {''.join(r.split(None, 2)[:2]): [int(x) for x in r.split()[2:]] for r in f}

>>> res
{'a0': [45, 124, 234, 53, 12, 34],
 'a180': [89, 63, 84, 73, 63, 83],
 'a90': [294, 32, 545, 190, 87]}

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

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