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

如何将嵌套字典转为列表并合并?优化嵌套字典遍历方法

Solution: Avoid Manual Key Checks & Merge Values Cleanly

Instead of hardcoding checks for each face card, we can handle the nested structure dynamically by checking the type of each value in card_values, then collect all the numeric values directly. Since your desired output has unique values in order, we'll also deduplicate and sort the final list to match exactly what you need.

Refactored Code

card_values = {
    "normal": [2, 3, 4, 5, 6, 7, 8, 9, 10], 
    "suited": {"J":10, "Q":10, "K":10, "A":11}
}

all_cards = []
# Iterate directly over the values in the dictionary (not keys)
for value_group in card_values.values():
    if isinstance(value_group, list):
        # Add all elements from the numeric list
        all_cards.extend(value_group)
    elif isinstance(value_group, dict):
        # Pull all values from the face card dict (no key checks needed!)
        all_cards.extend(value_group.values())

# Remove duplicates and sort to match your target output
all_cards = sorted(list(set(all_cards)))
print(all_cards)

Output

[2, 3, 4, 5, 6, 7, 8, 9, 10, 11]

Breakdown of How This Works

  • We loop through values of card_values directly, so we don’t have to hardcode references to "normal" or "suited".
  • For each group:
    • If it’s a list (like the normal set), we use extend() to add every element to our result list.
    • If it’s a dictionary (like the suited face cards), we grab all its values with value_group.values() and add those—no manual checks for J/Q/K/A required!
  • Finally, we convert the list to a set to eliminate duplicate entries (since 10 appears multiple times), convert back to a list, and sort it to get the ordered result you specified.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 18:55:16