在Python中从文件中读取字典

时间:2017-11-15 18:02:32

标签: python python-3.x

我有一大堆储物柜分配给具有这种结构的文件中的人:

'paul':'locker.01'
'robert':'locker.02'
'julia':'locker.03'
'rosalind':'locker.04'

我需要创建一个脚本,将该文件读取为字典,如下所示:

{'paul':locker.01
'robert':locker.02
'julia':locker.03
'rosalind':locker.04}

到目前为止,我已经创建了这个脚本但是我被卡住了。以前有人这么做过吗?

f = open('C:/file.txt', 'r')
for i in f.readlines():
    i = i[0:-1]    
    print(i)

1 个答案:

答案 0 :(得分:1)

只是做:

result = {}
with open('thefile.txt') as my_file:
    for line in my_file:
        name, locker_number = line.replace("'", "").split(':')
        result[name] = locker_number
print(result)

请注意,这样做可能不是一个好方法。如果有两个Peter,三个Julias怎么办?

所以也许这对你更好:

result = {}
with open('thefile.txt') as my_file:
    for line in my_file:
        name, locker_number = line.replace("'", "").split(':')
        if not name in result:
            result[name] = [locker_number]
        else:
            result[name].append(locker_number)

print(result)

for name in result:
    result[name] = ', '.join(result[name])  # will return a string of comma separated lockers.

print(result)

这会创建一个分配给该名称的储物柜编号列表。