Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
169 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 Answer

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...