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

如何实现随机展示字典的键或值并显示对应配对项?

解决方案

要实现随机展示字典的键或值,再显示对应配对项,可以按以下思路修改代码:

核心思路

  • 先随机决定本次要展示的是键还是值
  • 若展示键,直接用原字典取值;若展示值,通过反向字典快速找到对应的键

修改后的完整代码

import random

alphabet = {'1':'A','2':'B','3':'C','4':'D'}
# 生成反向字典,用于通过值找键
reverse_alphabet = {v: k for k, v in alphabet.items()}

# 随机选择展示类型:键或值
display_type = random.choice(['key', 'value'])

if display_type == 'key':
    # 随机选一个键
    selected = random.choice(list(alphabet.keys()))
    print(f'Guess corresponding value: {selected}')
    input('Press return to see corresponding value')
    print(alphabet[selected])
else:
    # 随机选一个值
    selected = random.choice(list(alphabet.values()))
    print(f'Guess corresponding key: {selected}')
    input('Press return to see corresponding key')
    print(reverse_alphabet[selected])

代码说明

  1. 反向字典:reverse_alphabet 把原字典的键值对反转,比如原字典中'2':'B',反向字典里就是'B':'2',这样通过值找键时不用遍历原字典,效率更高。
  2. 随机展示类型:用random.choice(['key', 'value'])随机决定本次展示键还是值。
  3. 分支处理:根据展示类型分别处理键和值的展示、配对项查询逻辑。

内容的提问来源于stack exchange,提问作者nowmakeshift0

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 19:06:32