簡體   English   中英

嵌套字典鍵從 Int 更改為 Str

[英]Nested Dictionary Key changing from Int to Str

我希望將字典保存為 json 文件。 在實現保存用戶輸入的方法之前,我的嵌套字典中的原始鍵始終是一個 int,但現在它被保存到一個 json 文件中,它已被轉換為一個字符串。 有什么辦法可以將嵌套字典鍵保存為 int 而不是字符串? 以下是存儲在我的 json 文件中的內容:

{"1": {"Recipe Name": "Sourdough bread", "Category": "Rustic Breads", "Preptime": "18 hours", "Cooktime": "1 hour", "Ingredients": "Flour, Water, Starter", "Instructions": "Mix and Bake"}}

編輯:我注意到 json 文件總是將它們保存為字符串值。 在我的代碼邏輯中,我允許用戶將數字(在本例中為數字 1)輸入到 select 他們想要查看、編輯或刪除的食譜,我使用 isinstance(參見下面的示例)來驗證用戶正在輸入一個 in int 以確保他們無法輸入字符串。

if int(edit_selection) == isinstance(int(edit_selection), int):

如果將用戶輸入轉換為字符串,我該怎么做才能驗證用戶輸入是否與該數字相對應,我是否需要創建一個數字列表(字符串),讓我們說 1 到 500 以供檢查?

您是否正在努力實現這一目標:

my_list = {"1": {"Recipe Name": "Sourdough bread", "Category": "Rustic Breads", "Preptime": "18 hours", "Cooktime": "1 hour", "Ingredients": "Flour, Water, Starter", "Instructions": "Mix and Bake"}}
output_dict = {}
for key, value in my_list.items():
    output_dict[int(key)] = value

print(output_dict)

output 是: {1: {'Recipe Name': 'Sourdough bread', 'Category': 'Rustic Breads', 'Preptime': '18 hours', 'Cooktime': '1 hour', 'Ingredients': 'Flour, Water, Starter', 'Instructions': 'Mix and Bake'}}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM