Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 将字符串转换为具有正确类型的字典变量_Python_String_Dictionary - Fatal编程技术网

Python 将字符串转换为具有正确类型的字典变量

Python 将字符串转换为具有正确类型的字典变量,python,string,dictionary,Python,String,Dictionary,我正在创建一个应用程序,其中有一个Dictionary(由特定的加密算法生成)变量,并将其保存到文本文件中。我检索变量并再次将其转换为字典,如下所示: f = open( '/sk.txt') t_ref = f.read() requested_encrypted_file = ast.literal_eval(t_ref) print type(requested_encrypted_file) f.close() 包含密文重要信息的字典变量具有以下形式: {'msg': '{"ALG":

我正在创建一个应用程序,其中有一个Dictionary(由特定的加密算法生成)变量,并将其保存到文本文件中。我检索变量并再次将其转换为字典,如下所示:

f = open( '/sk.txt')
t_ref = f.read()
requested_encrypted_file = ast.literal_eval(t_ref)
print type(requested_encrypted_file)
f.close()
包含密文重要信息的字典变量具有以下形式:

{'msg': '{"ALG": 0, "CipherText": "xcUHHV3ifPJKFqB8aL9fzQ==", "MODE": 2, "IV": "2Y2xDI+a7JRt7Zu6Vtq86g=="}', 'alg': 'HMAC_SHA1', 'digest': '4920934247257f548f3ca295455f5109c2bea437'}
问题是,当我从文件中检索这个变量时,所有字段都是str,而不是保存到txt文件之前的类型?有没有一种简单的方法可以用正确的类型检索它们


如果您只需要处理基本数据类型,请保存并加载JSON序列化的数据

import json

a = {'foo': 'bar', 'baz': 42, 'biz': True}

# Save
with open('test.txt', 'w') as outf:
    json.dump(a, outf)

# Read
with open('test.txt', 'r') as inf:
    b = json.load(inf)
b

{'baz':42,'biz':True,'foo':'bar'}

我将使用模块
将Python数据结构转储为可序列化的数据,然后
加载

pickle.dump(dictionary, open('data.p', 'w')) # write file with dictionary structure
savedData = pickle.load(open('data.p', 'r')) # reads the written file as dictionary

如何将字典保存到文件中?如下所示:f=open('/sk.txt',w')f.write(str(ciphertext))f.close()如果
ciphertext
包含您显示的值,则所有键和值都是字符串。是否希望键
msg
的值类型为
dict
?如果是这样,问题是生成写入文件的值。如果删除msg值周围的单引号,那么代码的工作方式就是这样。