如何将文件转换成字典?
我有一个文件包含两列,即,
1 a 2 b 3 c
我希望将这个文件读到一个字典中,第1列是键,第2列是值,
d = {1:'a', 2:'b', 3:'c'}
该文件很小,所以效率不是问题。
d = {} with open("file.txt") as f: for line in f: (key, val) = line.split() d[int(key)] = val
这将把键作为一个string:
with open('infile.txt') as f: d = dict(x.rstrip().split(None, 1) for x in f)
如果你的Python版本是2.7+,你也可以使用一个字典理解,如:
with open('infile.txt') as f: {int(k): v for line in f for (k, v) in (line.strip().split(None, 1),)}
def get_pair(line): key, sep, value = line.strip().partition(" ") return int(key), value with open("file.txt") as fd: d = dict(get_pair(line) for line in fd)
import re my_file = open('file.txt','r') d = {} for i in my_file: g = re.search(r'(\d+)\s+(.*)', i) # glob line containing an int and a string d[int(g.group(1))] = g.group(2)
如果你喜欢一件衬衫,试试:
d=eval('{'+re.sub('\'[\s]*?\'','\':\'',re.sub(r'([^'+input('SEP: ')+',]+)','\''+r'\1'+'\'',open(input('FILE: ')).read().rstrip('\n').replace('\n',',')))+'}')
inputFILE =文件path,SEP =键值分隔符
不是最优雅或有效的方式做,但相当有趣的:)
恕我直言,有点pythonic使用发电机(可能你需要2.7 +这个):
with open('infile.txt') as fd: pairs = (line.split(None) for line in fd) res = {int(pair[0]):pair[1] for pair in pairs if len(pair) == 2 and pair[0].isdigit()}
这也会过滤掉不以整数或不包含两个项目开始的行
这是另一个select…
events = {} for line in csv.reader(open(os.path.join(path, 'events.txt'), "rb")): if line[0][0] == "#": continue events[line[0]] = line[1] if len(line) == 2 else line[1:]