我正在使用文件的值来创建填充字典。我使用函数创建了文件:
def save_dict_to_file(filename, dictionary): # done
with open(filename, 'w') as w:
for key in dictionary:
w.write("(")
w.write(key)
w.write(")")
w.write("@(")
w.write(str(dictionary[key]))
w.write(")")
w.write("\n")
print (save_dict_to_file('save_dict_to_file_example.txt', {'abc':3,'def':'ghj'}))
原始文件内容:
(abc)@(3)
(def)@(ghj)
3 是整数。我想维护字典中的数据类型,但目前字典返回 '3' 作为字符串:
{'abc': '3', 'def': 'ghj'}
这是我的完整代码:
def load_dict_from_file(filename):
with open(filename, 'r') as r:
dictionary = dict()
file_contents=r.readlines()
for line in file_contents:
#line=line.strip()
index=line.index('@')
key=line[1:index-1] #before the @
value=line[index+2:-2] #after the @
value=value.strip()
dictionary[key]=value
for character in key,value:
if character.isdigit():
index_character=character.index
new_character = int(character)
else:
continue
print(dictionary)
如何从字典中删除旧字符并将其替换为新字符?
斯蒂芬大帝
当年话下
慕侠2389804
相关分类