1

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

Barmar
  • 741,623
  • 53
  • 500
  • 612

1 Answers1

2

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.

FlipTack
  • 413
  • 3
  • 15
  • Your example works as long as the keys do not have commas. – DYZ Dec 24 '16 at 22:35
  • Nope, that's not how CSV works. When there is a comma in a CSV field, it is escaped (`\,`): http://stackoverflow.com/questions/769621/dealing-with-commas-in-a-csv-file – DYZ Dec 24 '16 at 22:43
  • It' ok, I'm just warning the OP about its limitations. – DYZ Dec 24 '16 at 22:50
  • @DYZ i'll edit a description of the limitations into the post :) – FlipTack Dec 24 '16 at 22:51