简体   繁体   English

将字典的值以3列写入文件

[英]Write values of dictionary in columns of 3 to file

I would like to write the values of a dictionary in columns of 3 to a file in python. 我想将第3列中字典的值写入python中的文件。 The order of the values does not matter. 值的顺序无关紧要。

I have this dictionary dict_cols : 我有这个字典dict_cols

dict_cols = {'1': 'c1', 
             '2': 'c2', 
             '3': 'c3', 
             '4': 'c4', 
             '5': 'c5', 
             '6': 'c6'}

The following code writes all the values to a text file: 以下代码将所有值写入文本文件:

with open("output.txt", "w") as f:
    for k, v in dict_cols.items():
        f.write(v + ", ")

output.txt will have this content: output.txt将具有以下内容:

c1, c2, c3, c4, c5, c6, 

What do I modify the code to print out the following to output.txt in columns of 3, like the following? 我该如何修改代码以在第3列中将以下内容输出到output.txt ,如下所示?

c1, c2, c3,
c4, c5, c6

I am using python v3.6 我正在使用python v3.6

The main modification to your code would be to alternate the separator between a comma and a newline. 对代码的主要修改是在逗号和换行符之间交替使用分隔符。 Here's one way to do that with an enumeration to keep track of your position in the sequence: 这是通过枚举跟踪序列中位置的一种方法:

cols = 3
seps = ' ' * (cols - 1) + '\n'
with open("output.txt", "w") as f:
    for i, (k, v) in enumerate(dict_cols.items()):
        sep = '' if i == len(dict_cols) - 1 else ',' + seps[i % cols]
        f.write(v + sep)

This is a similar answer to @Mad Physicist's, but it doesn't use a list to hold the line endings (saves memory) and it only iterates over the values of the dictionary instead of the (unused) keys and values. 这与@Mad Physicist的答案类似,但是它不使用列表来保存行尾(节省内存),它仅遍历字典的值而不是(未使用的)键和值。

dict_cols = {'1': 'c1', 
             '2': 'c2', 
             '3': 'c3', 
             '4': 'c4', 
             '5': 'c5', 
             '6': 'c6'}

col = 1
with open('tmp.txt', 'w') as fp:
    for i, v in enumerate(dict_cols.values()):
        sep = '' if i == len(dict_cols) - 1 else ','
        fp.write(v + sep)
        if col == 3:
            fp.write('\n')
            col = 0
        col += 1

this is my way, if I have to be honest, I would choose @Ben's answer as it's less code,more efficient and easily readable, but this is how it works. 这是我的方式,如果我必须说实话,我会选择@Ben的答案,因为它的代码更少,效率更高且易于阅读,但这就是它的工作方式。 First I separate the different values of the list into the line they would be in. Then I take each value and print it. 首先,我将列表的不同值分隔到它们所在的行中。然后,我将每个值都打印出来。

file = "test.txt"
dict_cols = {'1': 'c1', 
             '2': 'c2', 
             '3': 'c3', 
             '4': 'c4', 
             '5': 'c5', 
             '6': 'c6'}
dict_values = dict_cols.values()
with open (file,"w") as f:
    count = -1
    sep_values = []
    for ind,value in enumerate(dict_values):
        if ind%3 ==0:
            count+=1
            sep_values.append("")
        if ind != len(dict_values)-1:
            end = ", "
        else:
            end = ""
        sep_values[count] += value+end
    for value in sep_values:
        f.write(value+"\n")

This is quite inelegant but works perfectly 这是非常优雅的,但效果很好

dict_cols = {'1': 'c1', '2': 'c2', '3': 'c3', '4': 'c4', '5': 'c5', '6': 'c6'}
line_sep = ',\n'

with open("output.txt", "w") as f:
    f.write(', '.join([v for v in dict_cols.values()][:3]) + line_sep + 
            ', '.join([v for v in dict_cols.values()][3:]))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM