Blue_Screen_Of_Death
Blue_Screen_Of_Death

Reputation: 15

How to convert a dictionary into a suitable format to save to file

I am new to python - however have encountered a problem

I have a file saved which looks like:

a,1
b,2
c,3

I can convert this to a dictionary by using this code:

file = open("dict.txt",'r')
dictionary = {}

    for line in file:
        x = line.split(",")
        key = x[0]
        value = x[1]
        value = value [:-1]
        dictionary[key] = value

There is code that allows the user to element (so dictionary now consists of a:1, b:2, c:3, d:4)

However, I need to get the dictionary in the form mentioned above

So

a,1
b,2
c,3
d,4

Is this possible?

Also if some explanations could go with the answer I'd appreciate it

Upvotes: 1

Views: 75

Answers (1)

FlipTack
FlipTack

Reputation: 423

For what you've specified, you can loop through a dictionary's key/value pairs using the items() function, and write each pair to the file:

data_dict = {'a': 1, 'b': 2, 'c': 3}

with open('data.txt', 'w') as file:
    for key, value in data_dict.items():
        file.write(str(key) + ',' + str(value) + '\n')

Of course, change data_dict to your dictionary, etc - this is just an example.

There are a couple of edge cases where this will not work, such as if either the key or the value contain commas. If you're looking to properly store comma-separated data, you may want to have a look at the builtin csv module.

Upvotes: 2

Related Questions