johnson
johnson

Reputation: 131

How to update dictionary on python?

So I'm working with creating a master dictionary while running a query for individual information.

Currently I have:

dictionary = {}
user_input =input('enter user id: ')
D = query(user_input)
dictionary[user_input] = D

And if I print dictionary[user_input] = D, I will get something like this:

{'user_input':[info]}

I want to prompt repeatedly and save all the individual information in one master dictionary and put it into a textfile.

How do I format my print so that when I try to print it to the textfile it's all written as one big dictionary?

What I've tried:

output_file = ('output.txt', 'w')
print(dictionary, file = output_file)
output_file.close()

This only seems to print {}

EDIT: Tried something diff. Since D already returns a dictionary, I tried:

dictionary.update(D) 

Which is supposed to add the dictionary that is stored in D to the dictionary right?

However, when I try printing dictionary:

print(dictionary)

#it returns: {}

Upvotes: 0

Views: 75

Answers (2)

fips
fips

Reputation: 4379

Use json.dump to write to the file. Then you can use json.load to load that data back to a dictionary object.

import json

with open('dictionary.txt', 'w') as f:
    json.dump(dictionary, f)

https://docs.python.org/3/library/json.html

EDIT: since you cannot use json maybe you can just separate the questions and answers with new lines like this. That will also be easy and clean to parse later:

with open('dictionary.txt', 'w') as f:
    for k,v in dictionary.items():
        f.write('%s=%s\n' % (k, v,))

Upvotes: 1

paloobi
paloobi

Reputation: 1

Not totally familiar with the issue, so I'm not sure if this is what you're looking for. But you don't need to print the assignment itself in order to get the value. You can just keep adding more things to the dictionary as you go, and then print the whole dictionary to file at the end of your script, like so:

dictionary = {}
user_input =input('enter user id: ')
D = query(user_input)
dictionary[user_input] = D

# do this more times....
# then eventually....

print(dictionary)

# or output to a file from here, as described in the other answer

Upvotes: 0

Related Questions