【问题标题】:Is there a way to use input to climb nested dictionaries?有没有办法使用输入来爬嵌套字典?
【发布时间】:2020-10-06 01:23:57
【问题描述】:

我开始收集游戏 Subnautica 中的所有食谱,最初使用列表,后来转向嵌套字典。在一位熟人的帮助下,我设法获得了所有类别的完整列表,如下所示。

SRI #Subnautica Recipe Index

fabricator
mobile
habitat
vehicle
scanner
modification
cyclops
neptune

Enter a choice > 

您输入名称,它会进入下一个类别和下一个类别,直到显示配方:

Enter a choice > titanium #user input
1 metal salvage

我的问题是,如果您碰巧输入错误,我不知道如何让输入能够“爬”备份类别/字典。这是允许下的代码。

def dive(dict_):
    print()
    for key in dict_:
        print(key)
    input_ = input("\nEnter a choice > ")
    if input_ in dict_ and isinstance(dict_[input_], dict):
        dive(dict_[input_])
    else:
        print(dict_[input_])

我一直在寻找解决方案,但我认为我的问题相当具体。除非我使用了错误或过于不明确的搜索字词,否则谷歌并没有提供太多帮助。如果可以的话,请帮忙。

【问题讨论】:

    标签: python python-3.x dictionary input nested


    【解决方案1】:

    有这个想法吗? (未经测试) 通过 dict 跟踪您的父路径:

    def dive(dict_, parents=[]):
        print()
        for key in dict_:
            print(key)
        if parents:
            print('back')
        input_ = input("\nEnter a choice > ")
        if input_ == 'back' and parents:
            dive(parents[-1], parents[:-1])
        elif input_ in dict_ and isinstance(dict_[input_], dict):
            dive(dict_[input_], parents+[dict_])
        else:
            print(dict_[input_])
    

    【讨论】:

    • 谢谢!只要您第一次正确拼写出来,它就可以工作。 =)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-12-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-19
    相关资源
    最近更新 更多