如何将文件转换成字典? [英] How to convert a file into a dictionary?

查看:148
本文介绍了如何将文件转换成字典?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含两列的文件,即

I have a file comprising two columns, i.e.,

1 a 
2 b 
3 c

我希望将此文件读到字典,以便列1是关键字,列2是该值,即

I wish to read this file to a dictionary such that column 1 is the key and column 2 is the value, i.e.,

d = {1:'a', 2:'b', 3:'c'}

文件很小,效率不是问题。

The file is small, so efficiency is not an issue.

推荐答案

d = {}
with open("file.txt") as f:
    for line in f:
       (key, val) = line.split()
       d[int(key)] = val

这篇关于如何将文件转换成字典?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆