从文本文件中创建字典:

时间:2016-04-10 00:22:29

标签: python python-3.x

我有一个这样的txt文件:

matt=Lives in oakland
drey=lives in San Francisco

我怎样才能制作这样的字典

{matt:Lives in oakland,drey:lives in San Francisco}

我使用了这段代码:

d = {}
with open('hints.txt', 'r') as f:
    for line in f:        
        name, residence = line.strip().split('=')
        d[name] = residence

它给了我这个错误:

ValueError: not enough values to unpack (expected 2, got 1)

2 个答案:

答案 0 :(得分:2)

'='上拆分,然后将其发送到dict()

with open('in.txt') as f:
    d = dict(line.strip().split('=') for line in f)

答案 1 :(得分:1)

循环划线,在=上拆分,并在此过程中构建dict

d = {}
with open('file.txt', 'r') as f:
    for line in f:        
        name, residence = line.strip().split('=')
        d[name] = residence