【问题标题】:Dictionary within a list - how to find values列表中的字典 - 如何查找值
【发布时间】:2016-03-31 17:59:22
【问题描述】:

我有一本包含大约 4000 个拉丁词及其英语含义的词典。我已经在 Python 中打开它并将其添加到列表中,它看起来像这样:

[{"rex":"king"},{"ego":"I"},{"a, ab":"away from"}...]

我希望用户能够输入他们正在寻找的拉丁词,然后程序会打印出英文含义。关于我如何做到这一点的任何想法?

【问题讨论】:

    标签: python-3.x dictionary


    【解决方案1】:

    您不应该将它们放在列表中。您可以使用主字典将所有项目保存在一个字典中,然后通过索引轻松访问相关含义。

    如果您从可迭代对象中获取小字典,您可以创建 main_dict,如下所示:

    main_dict = {}
    
    for dictionary in iterable_of_dict:
        main_dict.update(dictionary)
    
    word = None
    while word != "exit"
        word = input("Please enter your word (exit for exit): ")
        print(main_dict.get(word, "Sorry your word doesn't exist in dictionary!"))
    

    【讨论】:

      【解决方案2】:

      你可以循环浏览你的 4000 个项目...

      listr = [{"rex":"king"},{"ego":"I"},{"a, ab":"away from"}]
      out = "no match found"
      get = input("input please ")
      for c in range(0,len(listr)):
          try:
              out = listr[c][get]
              break
          except:
              pass
      print(out)
      

      也许您应该将现有列表按字母顺序排列成多个列表,以缩短搜索时间。 此外,如果条目与字典中的拉丁词不完全匹配,则它不会找到任何内容。

      【讨论】:

        猜你喜欢
        • 2013-06-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-10-06
        • 2014-03-14
        • 2019-02-14
        • 1970-01-01
        • 2022-01-22
        相关资源
        最近更新 更多