如何将嵌套字典转为列表并合并?优化嵌套字典遍历方法
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_valuesdirectly, so we don’t have to hardcode references to "normal" or "suited". - For each group:
- If it’s a list (like the
normalset), we useextend()to add every element to our result list. - If it’s a dictionary (like the
suitedface cards), we grab all its values withvalue_group.values()and add those—no manual checks for J/Q/K/A required!
- If it’s a list (like the
- 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
相关产品推荐
相关产品推荐

