Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting Text file to Dictionary

I have a text file called dict1.txt that contains two lines and I'd like to make the first string to give the keys and the second to give the values. The text file is

abcdefghijklmnopqrstuvwxyz

gikaclmnqrpoxzybdefhjstuvw

and the code I've been toying with is:

def read_cipherdef(fn):
d = {}
fn = open('dict1.txt', 'r')
for line in fn:
    key, val = line.split()
    d[(key)] = val

but in this case line.split() doesn't actually split the first line by character and it also gives a ValueError: too many values to unpack (expected 2).

Also I'm aware list(map(''.join, zip(*[iter('dict1.txt')]*1))) would split them up individually, but using that in conjunction with the existing code gives me another ValueError. So my question would be: how would I use all of this info here together to achieve my desired dictionary?

Thanks.

like image 785
clovis Avatar asked Jun 18 '26 08:06

clovis


2 Answers

Here's one way you can achieve that. Essentially, read the two lines, zip them and use them in a dict-comprehension.

>>> with open("/tmp/t") as f:
...     line1 = f.readline().strip()
...     line2 = f.readline().strip()
...     print({x:y for x, y in zip(line1, line2)})
... 
{'a': 'g', 'b': 'i', 'c': 'k', 'd': 'a', 'e': 'c', 'f': 'l', 'g': 'm', 'h': 'n', 'i': 'q', 'j': 'r', 'k': 'p', 'l': 'o', 'm': 'x', 'n': 'z', 'o': 'y', 'p': 'b', 'q': 'd', 'r': 'e', 's': 'f', 't': 'h', 'u': 'j', 'v': 's', 'w': 't', 'x': 'u', 'y': 'v', 'z': 'w'}

.. Or if you want a one-liner (this assumes there are only 2 lines in the file):

>>> with open("/tmp/t") as f:
...     print({x: y for x, y in zip(*[list(x.strip()) for x in f])})
... 
{'a': 'g', 'b': 'i', 'c': 'k', 'd': 'a', 'e': 'c', 'f': 'l', 'g': 'm', 'h': 'n', 'i': 'q', 'j': 'r', 'k': 'p', 'l': 'o', 'm': 'x', 'n': 'z', 'o': 'y', 'p': 'b', 'q': 'd', 'r': 'e', 's': 'f', 't': 'h', 'u': 'j', 'v': 's', 'w': 't', 'x': 'u', 'y': 'v', 'z': 'w'}
like image 180
UltraInstinct Avatar answered Jun 20 '26 22:06

UltraInstinct


How about this?

with open('dict1.txt') as f:
    lines=[line.strip('\n') for line in f.readlines()]
    d=dict(zip(lines[0],lines[1]))

from pprint import pprint
pprint(d)

Result:

{'a': 'g',
 'b': 'i',
 'c': 'k',
 'd': 'a',
 'e': 'c',
 'f': 'l',
 'g': 'm',
 'h': 'n',
 'i': 'q',
 'j': 'r',
 'k': 'p',
 'l': 'o',
 'm': 'x',
 'n': 'z',
 'o': 'y',
 'p': 'b',
 'q': 'd',
 'r': 'e',
 's': 'f',
 't': 'h',
 'u': 'j',
 'v': 's',
 'w': 't',
 'x': 'u',
 'y': 'v',
 'z': 'w'}
like image 31
nathanielng Avatar answered Jun 20 '26 23:06

nathanielng



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!