How Would I Make a Dictionary That Can Store User Input in Python

How to store users input into dictionary? Python

Your current code has two issues: first, it doesn't save the values of each student inside the loop. Second, it always rewrites the entire dictionary with a single key/value pair, that's why it doesn't work.

marks = {}

for i in range(10):
student_name = input("Enter student's name: ")
student_mark = input("Enter student's mark: ")
marks[student_name.title()] = student_mark

print(marks)

how can i keep/ save the user input in dictionary?

When you make and populate (fill) a dictionary in a running Python program, that dictionary only exists as long as the program is running. When you close the program - that memory is wiped and any modifications that are made are not stored.

As Tomerikoo pointed out, this solution: shelving dictionaries will allow you to preserve your dictionary after the program is closed.
I copy the code from the link (jabaldonedo's solution) and annotate it for you for clarity.

import shelve  # this is a Python library that allows you to store dictionaries after the program is closed
data = {'foo':'foo value'} # this is a mock-up dictionary. "words" in your case
d = shelve.open('myfile.db') # this creates a storage container in the program folder that can store multiple dictionaries. You can see this file appear when this code runs.
d['data'] = data # you make a section in that storage container, give it a name, e.g. "data" in this case, and store your dictionary in that section. You will store your "words" here.
d.close() # close the storage container if you do not intend to put anything else inside.

When you close and open up the program, the dictionary will not automatically pop into your running memory - you need to write code to access it. It can be made as an option in your game menu, e.g. "Load existing dictionary of words".

Back to jabaldonedo's solution:

import shelve  # no need to import again, if you are writing in the same python program, this is for demonstration
d = shelve.open('myfile.db') # open the storage container where you put the dictionary
data = d['data'] # pull out the section, where you stored the dictionary and save it into a dictionary variable in the running program. You can now use it normally.
d.close() # close the storage container if you do not intend to use it for now.

EDIT: Here is how this could be used in the specific context provided in your answer. Note that I imported an additional library and changed the flags in your shelve access commands.

As I mentioned in my comment, you should first attempt to load the dictionary before writing new things into it:

import shelve
import dbm # this import is necessary to handle the custom exception when shelve tries to load a missing file as "read"


def save_dict(dict_to_be_saved): # your original function, parameter renamed to not shadow outer scope
with shelve.open('shelve2.db', 'c') as s: # Don't think you needed WriteBack, "c" flag used to create dictionary
s['Dict'] = dict_to_be_saved # just as you had it


def load_dict(): # loading dictionary
try: # file might not exist when we try to open it
with shelve.open('shelve2.db', 'r') as s: # the "r" flag used to only read the dictionary
my_saved_dict = s['Dict'] # load and assign to a variable
return my_saved_dict # give the contents of the dictionary back to the program
except dbm.error: # if the file is not there to load, this error happens, so we suppress it...
print("Could not find a saved dictionary, returning a blank one.")
return {} # ... and return an empty dictionary instead


words = load_dict() # first we attempt to load previous dictionary, or make a blank one

ask = input('Do you want to add a new word?(y/n): ')
if ask == 'y':
new_word = input('what is the new word?: ')
word_meaning = input('what does the word mean?: ')
words[new_word] = word_meaning
save_dict(words)
elif ask == 'n':
print(words) # You can see that the dictionary is preserved between runs
print("Oh well, nothing else to do here then.")


How to create value in dictionary by user's input?

First, I recommend choosing a different name for your input function. If you want to keep using the builtin input, then you must not overwrite its name with your own function. How about get_input instead?

One way to prevent your dictionary from calling all your inputs right away is to wrap each value in a lambda. This makes each value an anonymous function object, and none of them will execute unless you call them explicitly.

def get_input():
print("1 - Albums list\n2 - List of songs in a album\n3 - Get song length")
print("4- Get lyrics song\n5 - Which album is the song in?")
print("6 - Search Song by Name\n7 - Search Song by Lyrics in Song\n8 - Exit")
x = request_creator(input())
print(x)

def request_creator(x):
return {
'1': lambda: "1#",
'2': lambda: "2#" + input("Enter album: "),
'3': lambda: "3#" + input("Enter song: "),
'4': lambda: "4#" + input("Enter song: "),
'5': lambda: "5#" + input("Enter song: "),
'6': lambda: "6#" + input("Enter a word: "),
'7': lambda: "7#" + input("Enter lyrics: "),
'8': lambda: "8#"
}[x]()

get_input()

Result:

1 - Albums list
2 - List of songs in a album
3 - Get song length
4- Get lyrics song
5 - Which album is the song in?
6 - Search Song by Name
7 - Search Song by Lyrics in Song
8 - Exit
3
Enter song: hey jude
3#hey jude

If you don't feel comfortable with lambdas, you can instead store just the text of each prompt in a dictionary (or None if the option requires no prompt). Then you can fetch that string and call input with it (or skip calling input entirely).

def get_input():
print("1 - Albums list\n2 - List of songs in a album\n3 - Get song length")
print("4- Get lyrics song\n5 - Which album is the song in?")
print("6 - Search Song by Name\n7 - Search Song by Lyrics in Song\n8 - Exit")
x = request_creator(input())
print(x)

def request_creator(x):
prompts = {
'1': None,
'2': "Enter album: ",
'3': "Enter song: ",
'4': "Enter song: ",
'5': "Enter song: ",
'6': "Enter a word: ",
'7': "Enter lyrics: ",
'8': None
}
result = x + "#"
prompt = prompts[x]
if prompt is not None:
result += input(prompt)
return result

get_input()


Related Topics



Leave a reply



Submit