Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
171 views
in Technique[技术] by (71.8m points)

python - Writing dictionary list values to a text file

I have the following dictionary that contains a list for each of its values

dictionary = { 
               0 : [2, 5] 
               1 : [1, 4]
               2 : [3]
             }

I need to output the values in a file like this

2 5
1 4
3

At the last digit of each row i need to have a space.

I have already tried to use this code

with open('test.txt', 'w') as f:
    for value in dictionary.values():
        f.write('{}
'.format(value))

so i want to omit the [] and the , of the output.

I have also tried to save the values of dictionary into a lists of list and then handle list instead of dictionary. But it's not the wisest thing i guess. Numbers are also saved on wrong order and brackets and commas are save too.

a = list(dictionary.values())
for i in a:
    with open('test.txt', 'w') as f:
        for item in a:
            f.write("%s
" % item)

because i get this output

[3, 2]
[5, 1]
[4]
question from:https://stackoverflow.com/questions/65644479/writing-dictionary-list-values-to-a-text-file

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Your first version is pretty close, so let's improve on that.

What you can do, is use a list comprehension to iterate through and convert each integer into a string. Then call join on the resulting list of strings.

Something like the following should work:

dictionary = { 
    0: [2, 5],
    1: [1, 4],
    2: [3]
}

with open('test.txt', 'w') as f:
    for value in dictionary.values():
        print(' '.join([str(s) for s in value]), file=f)

Side note: I've replaced f.write with print, to avoid manually specifying a newline character.

If you want a trailing space character on each line, you can either do this using f-strings:

print(f"{' '.join([str(s) for s in value])} ", file=f)

or traditional string concatenation:

print(' '.join([str(s) for s in value]) + ' ', file=f)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...