用新值替换Python字典值
我正在使用文件的值来创建和填充字典。我使用以下函数创建了该文件:用新值替换Python字典值,python,dictionary,Python,Dictionary,我正在使用文件的值来创建和填充字典。我使用以下函数创建了该文件: 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("@(
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)
如何从字典中删除旧字符并用新字符替换 希望在这段陌生的日子里一切都顺利 首先,您可以通过使用格式简化代码的编写
def save_dict_to_file(filename, dictionary): # done
with open(filename, 'w') as w:
for key in dictionary:
w.write("({})@({})\n".format(key, dictionary[key]))
但是有更简单的方法将字典保存到文件中。例如,您可以简单地将其写入文件或对其进行pickle
对于装载部件:
def load_dict_from_file(filename):
with open(filename, 'r') as r:
dictionary = {}
file_contents = r.readlines()
for line in file_contents:
key, value = line.split('@')
if key.isdigit():
key = int(key.strip())
if value.isdigit():
value = int(value.strip())
dictionary[key]=value
print(dictionary)
您正在测试解码时的数字,但您可以尝试将其设置为
int
,并在失败时捕获异常
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()
# see if its an int
try:
value = int(value)
execpt ValueError:
pass
dictionary[key]=value
print(dictionary)
我要回答你的问题。如果我误解了,请纠正我 我想你是在问,你怎么能把txt文件中的数字读作整数。不幸的是,我不完全知道这个文件的用途或结构是什么,但我猜它正在将@符号左侧括号内的文本映射到@符号右侧括号内的文本。根据您的代码文件示例,这将是
{'abc':3'def':'ghj'}
要做到这一点,您可以使用python字符串方法.isdigit()并在返回true时转换为int,或者如果您认为大多数值都是整数,您也可以尝试使用ValueError将其去掉。以下是两种方法:
# PSEUDOCODE
file_dictionary = {}
for each line in file:
key = ...
value = ...
# HERE GOES SOLUTION 1 OR 2
解决方案1:
if value.isdigit():
file_dictionary[key] = int(value)
else:
file_dictionary[key] = value
解决方案2:(如果知道大多数是整数,速度会更快,但如果相反,速度会更慢)
如果要编辑字典值,只需访问要编辑的值并将其指定给其他值即可。例如:file\u字典['abc']=3
如果要编辑密钥,必须指定新密钥的值并删除旧密钥。例:
file_dictionary = {'abd' = 3} # Create the dictionary
file_dictionary['abc'] = 3 # file_dictionary now = {'abc': 3, 'abd': 3}
file_dictionary.pop('abd') # file_dictionary now = {'abc': 3}
请包括示例代码并将示例数据放入问题中,而不是png的链接。欢迎使用堆栈溢出!请澄清您的具体问题或添加其他详细信息,以突出显示您所需的内容。正如目前所写的,很难准确地说出你在问什么。请参阅本页以获取澄清此问题的帮助。我不熟悉文件格式-它是什么编写的,也不熟悉如何读取和解析以生成dict。您能提供更多信息吗?Hi@tdelaney谢谢您的提问,刚刚添加了有关文件格式的更多上下文。您可以使用
pickle
轻松地将对象保存到文件中。当然,手工操作是很好的训练。我认为这是实现你想要的最简单的方法。转换键和值。
file_dictionary = {'abd' = 3} # Create the dictionary
file_dictionary['abc'] = 3 # file_dictionary now = {'abc': 3, 'abd': 3}
file_dictionary.pop('abd') # file_dictionary now = {'abc': 3}