Chris Charley
Chris Charley

Reputation: 6573

Parsing a key, value from file into dictionary using dictionary comprehension

I have looked around this site for examples like mine, but could find no answers.

The file I'm parsing is a simple file with key value pairs separated by a colon.

one:two
three:four
five:six
seven:eight
nine:ten
sample:demo

I thought there should be a simple solution using dictionary comprehension.

My first attempt was

fin = open('f00.txt', 'r')

L = {kv[0]:kv[1] for line in fin for kv in line.strip().split(':')}

this produced

{'o': 'n', 't': 'e', 'f': 'i', 's': 'a', 'e': 'i', 'n': 'i', 'd': 'e'}

The one way I was able to get results was this

L = {line.strip().split(':')[0]:line.strip().split(':')[1] for line in fin}

But that required calling split twice (indexed by 0 and 1)

Another way I was able to get results was:

d = {}
for line in fin:
    kv = line.strip().split(':')
    d[kv[0]] = kv[1]

{'one': 'two', 'three': 'four', 'five': 'six', 'seven': 'eight', 'nine': 'ten', 'sample': 'demo'}

Just wondering if there is a simple comprehension for what is a trivial task.

Thanks for any imput you might provide.

Upvotes: 3

Views: 133

Answers (2)

brentertainer
brentertainer

Reputation: 2188

with open('f00.txt', 'r') as fh:
    d = dict(line.strip().split(':') for line in fh)

Upvotes: 1

Ajax1234
Ajax1234

Reputation: 71451

You can use dict with a comprehension:

result = dict(i.strip('\n').split(':') for i in open('filename.txt'))

Output:

{'one': 'two', 'three': 'four', 'five': 'six', 'seven': 'eight', 'nine': 'ten', 'sample': 'demo'}

Upvotes: 3

Related Questions