問題
我想構建一個嵌套字典,用戶在 Python 中輸入鍵和值。下面是字典的一個例子。
dict = {series_name: {char_name: wishlist}}
此處series_name、char_name和wishlist由用戶輸入。用戶也可以為特定系列添加多個char_name。
例子
dict = {'naruto': {'itachi': 200, 'hinata': 100}, 'one piece': {'monkey': 1000, 'zoro': 1023}}
uj5u.com熱心網友回復:
那么對于 json 部分,您可以使用模塊 json。至于其余的,你需要做這樣的事情:
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)
uj5u.com熱心網友回復:
我感到無聊并想出了一個可能的解決方案。由于我使用了海象 ( :=),您至少需要 python 3.8 才能運行此代碼。解釋在評論中。
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))
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/397748.html
