Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 845
Chris Charley Avatar asked Dec 01 '25 01:12

Chris Charley


2 Answers

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'}
like image 52
Ajax1234 Avatar answered Dec 04 '25 11:12

Ajax1234


with open('f00.txt', 'r') as fh:
    d = dict(line.strip().split(':') for line in fh)
like image 30
brentertainer Avatar answered Dec 04 '25 13:12

brentertainer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!