【问题标题】:how do i traverse nested dictionaries (python)?我如何遍历嵌套字典(python)?
【发布时间】:2015-06-03 02:14:49
【问题描述】:

我对python非常陌生,所以如果我有什么不明白的地方请见谅!!

我有 125 行代码,但我有一个问题部分。由于它目前的设置,有一个拼写错误的单词。它链接到字典中拼写相似的单词,并且这些单词根据它们的相似程度进行评分。

possible_replacements("sineaster", {"sineaster":{"easter":0.75, "sinister":0.60}})

possible_replacements 是函数的名称,“sineaster”是拼写错误的单词,“easter”和“sinister”是推荐的替代品。我想访问字典单词(.75 和 .6)的相关数字,但我似乎无法访问它们,因为它们嵌套在另一个字典中。

有什么建议吗?

【问题讨论】:

标签: python dictionary nested


【解决方案1】:

一旦您知道要查询哪个词(此处为“sineaster”),您只需一个简单的 dictionary,例如,您可以在 for 循环中遍历:

outer_dict = {"sineaster":{"easter":0.75, "sinister":0.60}}
inner_dict = outer_dict["sineaster"]
for key, value in inner_dict.items():
    print('{}: {}'.format(key, value))

【讨论】:

  • 它说“'builtin_function_or_method' 对象不可迭代”?
  • 确实,对不起,是inner_dict.items(),我更正了答案。
  • 我修改了它,我得到了我需要的东西!我非常感谢你,你为我节省了很多时间。老实说,这很棒。非常感谢!!
【解决方案2】:

我假设您的替换字典大于单个条目。如果是这样,请考虑一种可以实现possible_replacements 的方法:

def possible_replacements(misspelled, replacement_dict):
    suggestions = replacement_dict[misspelled]
    for (repl, acc) in suggestions.items():
        print("[%.2f] %s -> %s" % (acc, misspelled, repl))

# This is the replacement dictionary, with an extra entry just to illustrate
replacement_dict = {
    "sineaster":{"easter":0.75, "sinister":0.60},
    "adn": {"and": 0.99, "end": 0.01}
}

# Call function, asking for replacements of "sineaster"
possible_replacements("sineaster", replacement_dict)

输出:

[0.75] sineaster -> 复活节 [0.60] 险恶 -> 险恶

在这种情况下,它只是打印出可能替换的列表,以及相应的概率(我假设)。

当你在函数内部用“sineaster”调用它时,

suggestions = {"easter":0.75, "sinister":0.60}

suggestions.items() = [('easter', 0.75), ('sinister', 0.6)]

for 循环的第一次迭代中:

repl = "easter"
acc  = 0.75

在第二次迭代中:

repl = "sinister"
acc  = 0.60

您可以在函数内部使用任何合适的逻辑,我只是​​选择循环“建议”并显示它们。

【讨论】:

    猜你喜欢
    • 2013-07-21
    • 2017-07-25
    • 1970-01-01
    相关资源
    最近更新 更多