简体   繁体   中英

how do i traverse nested dictionaries (python)?

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?

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))

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM