如何获取保存在变量中的字典值对应的键?
Got it! The issue with your current code is that you’re only selecting a value from word_dict, so you lose the connection to its associated key. The simplest and most efficient fix is to pick a random key-value pair directly instead of just a value. Here’s how to adjust your code:
Recommended Approach (Clean & Efficient)
Instead of using word_dict.values(), use word_dict.items() which gives you tuples of (key, value). This way you get both the key and value in one random selection:
import random from words import word_dict def get_word_and_key(): # Pick a random (key, value) pair from the dictionary key, word = random.choice(list(word_dict.items())) return key, word.upper() # Example usage selected_key, selected_word = get_word_and_key() print(f"Selected Key: {selected_key}, Selected Word: {selected_word}")
Why this works:
word_dict.items()returns an iterable of all key-value pairs in the dictionary.- Converting it to a list (
list(word_dict.items())) letsrandom.choiceselect one pair at random. - We unpack the tuple into
keyandword, then return both (with the word uppercased as in your original code).
Alternative: If You Already Have the Value and Need the Key
If for some reason you can’t modify the original get_word() function and need to find the key after picking the value, you can loop through the dictionary to match the value. Note this is less efficient (especially for large dictionaries) and will only return the first matching key if multiple keys map to the same value:
def find_key_for_value(target_value): # Loop through all key-value pairs to find a match for key, value in word_dict.items(): if value.upper() == target_value: # Match case since get_word() returns upper() return key return None # Return None if the value isn't found in the dict # Using with your original function random_word = get_word() corresponding_key = find_key_for_value(random_word) print(f"Key for '{random_word}' is: {corresponding_key}")
Caveats for this approach:
- If multiple keys have the same value, this returns the first one encountered.
- It’s O(n) time complexity (checks every item until a match is found) versus the first approach which is O(1) for the selection.
Stick with the first approach whenever possible—it’s cleaner, faster, and avoids potential edge cases with duplicate values.
内容的提问来源于stack exchange,提问作者Fahim islam

