我是python的新手,我正在开发一个需要将字典写入文本文件的项目。格式如下:
{'17': [('25', 5), ('23', 3)], '12': [('28', 3), ('22', 3)], '13': [('28', 3), ('23', 3)], '16': [('22', 3), ('21', 3)], '11': [('28', 3), ('29', 1)], '14': [('22', 3), ('23', 3)], '15': [('26', 2), ('24', 2)]}.
如您所见,字典中的值始终是列表。我想在下面写入文本文件: 17,25,5 \ n 17,23,3 \ n 12,28,3 \ n 12,22,3 \ n 13,28,3 \ n 13,23,3 \ n ... \ n代表新行
这意味着,要为列表中的每个值重复的键都属于'那些钥匙。原因是因为我需要再次将文本文件读入数据库以进行进一步分析。 尝试搜索过去几天的答案并尝试了很多方法,只是无法使其成为这种格式。感谢您是否有任何解决方案。 非常感谢!
答案 0 :(得分:0)
>>> for k, v in data.items():
... for t in v:
... print "%s, %s, %s" % ((k,) +t)
...
11, 28, 3
11, 29, 1
13, 28, 3
13, 23, 3
12, 28, 3
12, 22, 3
15, 26, 2
15, 24, 2
14, 22, 3
14, 23, 3
17, 25, 5
17, 23, 3
16, 22, 3
16, 21, 3
>>>
首先获取每个键和值(它们是元组)。然后循环遍历元组并使用键打印每个元组值。请注意,字典不是有序的,因此结果可能不会按字典顺序排列
答案 1 :(得分:0)
这是一个工作示例,向您展示如何将字典转储到字符串,首先没有任何特定顺序,然后按键排序,选择您想要的:
data = {
'17': [('25', 5), ('23', 3)],
'12': [('28', 3), ('22', 3)],
'13': [('28', 3), ('23', 3)],
'16': [('22', 3), ('21', 3)],
'11': [('28', 3), ('29', 1)],
'14': [('22', 3), ('23', 3)],
'15': [('26', 2), ('24', 2)]
}
lines = []
for k, v in data.iteritems():
for tupl in v:
row = [k] + map(lambda x: str(x), list(tupl))
lines.append(', '.join(row))
output = '\n'.join(lines)
print output
print '-' * 80
lines = []
for k, v in sorted(data.iteritems()):
for tupl in v:
row = [k] + map(lambda x: str(x), list(tupl))
lines.append(', '.join(row))
sorted_output = '\n'.join(lines)
print sorted_output
修改强>
上面的代码是为了与python 2.x一起编写的,这里是3.x版本:
data = {
'17': [('25', 5), ('23', 3)],
'12': [('28', 3), ('22', 3)],
'13': [('28', 3), ('23', 3)],
'16': [('22', 3), ('21', 3)],
'11': [('28', 3), ('29', 1)],
'14': [('22', 3), ('23', 3)],
'15': [('26', 2), ('24', 2)]
}
lines = []
for k, v in data.items():
for tupl in v:
row = [k] + list(map(lambda x: str(x), list(tupl)))
lines.append(', '.join(row))
output = '\n'.join(lines)
print(output)
print('-' * 80)
lines = []
for k, v in sorted(data.items()):
for tupl in v:
row = [k] + list(map(lambda x: str(x), list(tupl)))
lines.append(', '.join(row))
sorted_output = '\n'.join(lines)
print(sorted_output)
答案 2 :(得分:0)
假设散列值由包含大小为2的元组的列表组成。
>>> f = open('test.txt', 'w')
>>> for key,value in d.iteritems():
... for v in value:
... f.write(key + ' ' + v[0] + ' ' + str(v[1]) + '\n')
...
>>> f.close()
test.txt中的值将为
11, 28, 3
11, 29, 1
13, 28, 3
13, 23, 3
12, 28, 3
12, 22, 3
15, 26, 2
15, 24, 2
14, 22, 3
14, 23, 3
17, 25, 5
17, 23, 3
16, 22, 3
16, 21, 3