Read contents of a text file into a dictionary

时间:2015-12-06 21:45:29

标签: python python-2.7

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. 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

2 个答案:

答案 0 :(得分:2)

这可能会帮助你(毕竟圣诞节时间)

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)

输入文件

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

它产生

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

它基本上从文件中读取每一行,然后将其拆分为忽略空格的块。

然后使用前两个元素组成键,其余元素组成一个列表,将每个元素转换为整数。

我假设你想要数字作为整数。如果您想将它们作为字符串,则可以忽略转换为int

d[k] = els[2:]

答案 1 :(得分:1)

如果您喜欢单行(种类):

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]}