user5592141
user5592141

Reputation: 39

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

Upvotes: 0

Views: 75

Answers (2)

Pynchia
Pynchia

Reputation: 11590

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

d[k] = els[2:]

Upvotes: 2

Mike Müller
Mike Müller

Reputation: 85442

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

Upvotes: 1

Related Questions