Python 如何将文件转换为字典?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4803999/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to convert a file into a dictionary?
提问by Darren J. Fitzpatrick
I have a file comprising two columns, i.e.,
我有一个包含两列的文件,即
1 a
2 b
3 c
I wish to read this file to a dictionary such that column 1 is the key and column 2 is the value, i.e.,
我希望将此文件读入字典,以便第 1 列是键,第 2 列是值,即
d = {1:'a', 2:'b', 3:'c'}
The file is small, so efficiency is not an issue.
文件很小,所以效率不是问题。
采纳答案by Vlad H
d = {}
with open("file.txt") as f:
for line in f:
(key, val) = line.split()
d[int(key)] = val
回答by Ignacio Vazquez-Abrams
This will leave the key as a string:
这会将密钥保留为字符串:
with open('infile.txt') as f:
d = dict(x.rstrip().split(None, 1) for x in f)
回答by VGE
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)
回答by tokland
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)
回答by wim
If your python version is 2.7+, you can also use a dict comprehensionlike:
如果您的 python 版本是 2.7+,您还可以使用像这样的dict 理解:
with open('infile.txt') as f:
{int(k): v for line in f for (k, v) in (line.strip().split(None, 1),)}
回答by Holger Bille
IMHO a bit more pythonic to use generators (probably you need 2.7+ for this):
恕我直言,使用生成器需要更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()}
This will also filter out lines not starting with an integer or not containing exactly two items
这也将过滤掉不以整数开头或不包含两个项目的行
回答by srami
If you love one liners, try:
如果您喜欢一种衬垫,请尝试:
d=eval('{'+re.sub('\'[\s]*?\'','\':\'',re.sub(r'([^'+input('SEP: ')+',]+)','\''+r''+'\'',open(input('FILE: ')).read().rstrip('\n').replace('\n',',')))+'}')
Input FILE = Path to file, SEP = Key-Value separator character
输入 FILE = 文件路径,SEP = 键值分隔符
Not the most elegant or efficient way of doing it, but quite interesting nonetheless :)
不是最优雅或最有效的方式,但仍然很有趣:)
回答by Robel Robel Lingstuyl
Here's another option...
这是另一种选择...
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:]
回答by Samer Ayoub
By dictionary comprehension
通过字典理解
d = { line.split()[0] : line.split()[1] for line in open("file.txt") }
Or By pandas
或者由熊猫
import pandas as pd
d = pd.read_csv("file.txt", delimiter=" ", header = None).to_dict()[0]
回答by A. West
Simple Option
简单选项
Most methods for storing a dictionary use JSON, Pickle, or line reading. Providing you're not editing the dictionary outside of Python, this simple method should suffice for even complex dictionaries. Although Pickle will be better for larger dictionaries.
大多数存储字典的方法使用 JSON、Pickle 或行读取。如果您不是在 Python 之外编辑字典,这种简单的方法应该足以处理复杂的字典。尽管 Pickle 对于较大的字典会更好。
x = {1:'a', 2:'b', 3:'c'}
f = 'file.txt'
print(x, file=open(f,'w')) # file.txt >>> {1:'a', 2:'b', 3:'c'}
y = eval(open(f,'r').read())
print(x==y) # >>> True

