我需要从文件中读取字典项并将反向字典写入文件,但是我不知道为什么此代码无法正常工作。
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))
答案 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了。