简体   繁体   English

将文本文件读入字典

[英]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) . 如果您希望引发异常,请将next(f, '')更改为next(f) If you prefer a different default change next(f, '') to next(f, 'default') . 如果您希望使用其他默认值,请将next(f, '')更改为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         

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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