美文网首页
python读取txt文档或者excel文件内容,转换为字典

python读取txt文档或者excel文件内容,转换为字典

作者: 大大的世界和小小的人儿 | 来源:发表于2021-07-11 10:24 被阅读0次

    方法一

    这个方法适合1个key对应多个value的情况,也适合1个key对应1个value的情况。简单来说就是你的文档有多列或者只有两列数据。

    f = open('filename','r')    #读取文件
    new_dict = {}
    for line in f:
        f2  =  line.strip().split()
        new_dict[f2[0]]  =  f2[1]    #如果1个key有多个value,可以写成new_dict[f2[0]]  =  f2[1:]
    
    f.close()
    

    方法二

    这个方法仅适合1个key对应1个value的情况。简单来说就是你的文档只有两列数据。

    f = open('filename','r')
    L = [line.strip().split() for line in f]
    new_dict = dict(L)
    print(new_dict)
    f.close()
    

    相关文章

      网友评论

          本文标题:python读取txt文档或者excel文件内容,转换为字典

          本文链接:https://www.haomeiwen.com/subject/kclrpltx.html