0

i'm incredibly new to python so please forgive me if i don't understand something!!

I've got a 125 lines of code but I have one problem section. as it's currently set up, there is an incorrectly spelled word. it links to similarly spelled words in the dictionary, and the words have a score based off of how similar they are.

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

possible_replacements is the name of the function, "sineaster" is the misspelled word, and "easter" & "sinister" are recommended substitutes. I want to access the correlated numbers to the dictionary words (the .75 and .6), but I can't seem to reach them because they're nested within another dictionary.

any suggestions?

  • What do you meen. You can reach esaster, e.g. `my_dict["sineaster"]["easter"]` – Marcin Mar 30 '15 at 06:51
  • **See also:** https://stackoverflow.com/questions/7681301/search-for-a-key-in-a-nested-python-dictionary https://stackoverflow.com/a/16508328/42223 – dreftymac Oct 30 '17 at 19:55

2 Answers2

2

Once you know which word to query (here 'sineaster'), you just have a simple dictionary that you can, for example, traverse in a for loop:

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))
Francis Colas
  • 3,459
  • 2
  • 26
  • 31
0

I'm assuming your replacement dictionary is larger than a single entry. If so, consider one way you might implement 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)

Output:

[0.75] sineaster -> easter
[0.60] sineaster -> sinister

In this case, it just prints out a list of possible replacements, with the corresponding probability (I assume).

When you call it with "sineaster", inside the function,

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

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

And on the first iteration of the for loop:

repl = "easter"
acc  = 0.75

And on the second iteration:

repl = "sinister"
acc  = 0.60

You can use whatever logic is appropriate inside the function, I just choose to loop over the "suggestions" and display them.

jedwards
  • 29,432
  • 3
  • 65
  • 92