我尝试将数据从字典保存到文件,我的代码是:
mapping = {'a': 1, 'c': 5, 'b': 3, 'd': -4}
values = {'sample1': {'a': 12, 'c': 4, 'b': 10, 'd': 6}, 'sample3': {'a': 3, 'c': 9, 'b': 6, 'd': 10}, 'sample2': {'a': 5, 'c': 6, 'b': 8, 'd': 12}}
for dataset in values:
for key, value in mapping.items():
values[dataset][key] += value
with open(dataset + ".txt", 'w') as out:
out.write(dataset)
for key,value in values[dataset]:
out.write("{0},{1}\n".format(key,value))
但是当我运行它时,我收到一个错误:
Traceback (most recent call last):
for key,value in values[dataset]:
ValueError: need more than 1 value to unpack
关于什么是错的任何想法/提示?
干杯,凯特
答案 0 :(得分:2)
更改
for key,value in values[dataset]:
到
for key,value in values[dataset].items():
答案 1 :(得分:0)
正如其他人所指出的那样,您在的 中缺少项属性。
在不知道你想要完成什么的情况下,我会这样写:
mapping = {'a': 1, 'c': 5, 'b': 3, 'd': -4}
values = {'sample1': {'a': 12, 'c': 4, 'b': 10, 'd': 6}, 'sample3': {'a': 3, 'c': 9, 'b': 6, 'd': 10}, 'sample2': {'a': 5, 'c': 6, 'b': 8, 'd': 12}}
for dataset in values:
for key, value in mapping.items():
values[dataset][key] += value
with open(dataset + ".txt", 'w') as out:
out.write("{0}\n".format(dataset)) # for formatting purposes
# although you already have it in the file name
for key, value in values[dataset].items():
out.write("{0},{1}\n".format(key,value))