Problem
I want to construct a nested dictionar with user entering key and values in Python. Below is an example of the dictionary.
dict = {series_name: {char_name: wishlist}}
Here series_name , char_name and wishlist is entered by the user. Also user can add multiple char_name for particular series.
Example
dict = {'naruto': {'itachi': 200, 'hinata': 100}, 'one piece': {'monkey': 1000, 'zoro': 1023}}
CodePudding user response:
Well for the json part you can use the module json. As for the rest, you would need to do a thing like that:
my_series = dict()
stop_first = False
while not stop_first:
series_name = input("Name of the series: ")
if series_name == "None":
stop_first = True
else:
stop_second = False
my_series[series_name] = dict()
while not stop_second:
character_name = input("Name of the character: ")
if character_name == "None":
stop_second = True
else:
wishlist = int(input("Wishlist: "))
my_series[series_name][character_name] = wishlist
print(my_series)
CodePudding user response:
I got bored and came up with a possible solution. Due to my use of a walrus (:=
) you will need at least python 3.8 for this code to run. Explanations are in the comments.
import json
entries = dict() #represents a database of all current entries
def entry():
global entries
series = input("Input Series: ")
name = []
wishlist = []
#allows the user to add as many items as they like
#terminate this process by sending an empty line
while not ((n := input("Input Character Name or Press Return to Skip: ")) == ""):
name.append(n)
wishlist.append(input("Input Wishlist: "))
#create the series if it doesn't exist
if series not in entries:
entries[series] = dict()
#create the entries if they don't exist
for n, w in zip(name, wishlist):
if not n in entries[series]:
entries[series][n] = w
entry()
print(json.dumps(entries))