0

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: {}

2 Answers 2

1

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,))
Sign up to request clarification or add additional context in comments.

2 Comments

this is actually the way I'm familiar with, but I was told specifically not to use json....
Updated answer with alternative solution.
0

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

1 Comment

this is what i did and when i do print(dictionary) i get {}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.