反转文件列表

时间:2019-03-28 20:15:48

标签: python

我需要从文件中读取字典项并将反向字典写入文件,但是我不知道为什么此代码无法正常工作。

file = open("copy.txt", "w") 
file.write("'europe' : ['Romania', 'Italy', 'Greece', 'Netherlands', 'Austria', 'Vatican', 'Germany', 'Hungary', 'Bulgaria', 'CzechRepublic', 'Belgium', 'Scotland', 'Spain', 'Portugal', 'UnitedKingdom', 'Sweden', 'Ireland', 'Norway', 'Slovakia', 'Poland','France']") 
file.close()

fin = open('copy.txt')
for line in fin:
    word = line.strip()
    print(word)

def invert_dic(d):
    inverse = dict()
    for key in d:
        val = d[key]
        for x in val:
          inverse[x] = [key]
    return inverse

print(invert_dic(word))

1 个答案:

答案 0 :(得分:1)

您应该使用json来向/从文件写入/读取字典。

import json

continent_dict = {'europe' : ['Romania', 'Italy', 'Greece', 'Netherlands', 'Austria', 'Vatican', 'Germany', 'Hungary', 'Bulgaria', 'CzechRepublic', 'Belgium', 'Scotland', 'Spain', 'Portugal', 'UnitedKingdom', 'Sweden', 'Ireland', 'Norway', 'Slovakia', 'Poland','France']}

# dump continent dictionary to json file
with open('copy.json', 'w') as file:
    json.dump(continent_dict, file)

# load continent dictionary from json file
with open('copy.json', 'r') as file:
    loaded_dict = json.load(file)

现在,您将可以在loaded_dict上调用invert_dic了。