You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何获取保存在变量中的字典值对应的键?

How to Get the Corresponding Key for a Random Value from Your Dictionary

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:

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())) lets random.choice select one pair at random.
  • We unpack the tuple into key and word, 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 04:32:33