[英]How do I change the format of a dictionary to value1;key1; in Python 3.6?
I'm trying to change the format of a dictionary to 我正在尝试将字典的格式更改为
value1;key1;
value2;key2;
value3;key3;
valuen;keyn;
and to save it to a text file. 并将其保存到文本文件。
I also want to be able to load the text file and convert it back to a dictionary. 我还希望能够加载文本文件并将其转换回字典。 Also, the values and keys should be on the next row under each other but I couldn't make it look like that here. 另外,值和键应该在彼此之间的下一行上,但是我无法使其看起来像这里。
I tried to convert both keys and values to separate lists and put them together but I didn't get anywhere. 我试图将键和值都转换为单独的列表,然后将它们放在一起,但我一无所获。 Also tried other methods I found on StackOverflow but I couldn't get anything to work and now I'm completely stuck. 还尝试了我在StackOverflow上找到的其他方法,但是我什么都无法工作,现在我完全被卡住了。
Try this: 尝试这个:
dct = {'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}
with open('output.txt', 'w') as f:
for k, v in dct.items():
f.write('{};{};\n'.format(v, k))
Output: 输出:
value1;key1;
value2;key2;
value3;key3;
Assuming you have already opened your output file as f_out: 假设您已经以f_out打开输出文件:
for key, value in my_dict.items():
f_out.write('{};{};\n'.format(value, key))
will give you the desired output. 将为您提供所需的输出。 Reading it back in is also easy: 重新读回它也很容易:
for line in f_in:
my_list = line.split(';')
my_dict[my_list[1]] = my_list[0]
Here you go 干得好
# Writing
D = {"K1" : "V1", "K2" : "V2", "K3" : "V3"}
f = open("temp.txt", "w")
for k in D:
tempStr = k+";"+D[k]+";\n"
f.write(tempStr)
f.close()
# Reading
f = open("temp.txt", "r")
t1 = f.read().split()
D2 = dict()
for i in t1:
k, v, _ = i.split(";")
D2[k] = v
f.close()
print(D2["K2"])
In case you need something to read such a source text file, you can use this: 如果您需要某些东西来阅读这样的源文本文件,可以使用以下命令:
source = "source.txt"
def readFile(source):
d = dict()
with open(source) as f:
data = f.readlines()
for line in data:
l = line.split(";")
key, value = l[0], l[1]
d[key] = value
return d
dictionaryFromFile = readFile(source)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.