简体   繁体   中英

Read Text File into Dictionary

How can I read a text file in line by line and assign odd number lines to a dictionary's keys and the even number lines to a dictionary's values? For example, how could I make the below new line delimited list:

A
B
C
D
E
F
G
H

go into a dictionary like this:

dict{"A":"B","C":"D","E":"F","G":"H"}
with open(filename, 'r') as f:
    d = {}
    for line in f:
        d[line.strip()] = next(f, '').strip()

Note: If your file has an odd number of lines your last key will have a blank value. If you prefer an exception to be thrown change next(f, '') to next(f) . If you prefer a different default change next(f, '') to next(f, 'default') .

Another way:

with open(filename, 'r') as f:
    d = {k.strip():v.strip() for k, v in zip(f, f)}

Note that if the text file has an odd number of lines it will drop the last key.

To preserve the last key when there are an odd number of lines do:

from itertools import izip_longest, imap
with open(filename, 'r') as f:
    f = imap(str.strip, f)
    d = dict(izip_longest(f, f, fillvalue='default'))

Actually, you just have to read in a file and loop through it. If a line is odd, remember it as the value, if a line is even append it to the dictionary with the line as key.

import sys
import numpy as np

fn=sys.argv[1]

d={}

with open(fn,'rb') as f:

for i,line in enumerate(f):

    if np.mod(i+1,2)==0:
        d[lastVal]=line.replace('\n','')
    else:   
        lastVal=line.replace('\n','')

print d         

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM