【问题标题】:Python - Nested Dictionaries - Extracting ValuesPython - 嵌套字典 - 提取值
【发布时间】:2025-12-01 20:45:02
【问题描述】:

下面的嵌套字典存储了各个国家在不同城市(北京、伦敦、里约)获得的奥运奖牌数量。下面的代码还创建了一个包含美国赢得的奖牌数量的列表。有没有更 Pythonic、干净或有效的方法来获取该列表?

nested_d = {'Beijing':{'China':51, 'USA':36, 'Russia':22, 'Great Britain':19}, 'London':    {'USA':46, 'China':38, 'Great Britain':29, 'Russia':22}, 'Rio':{'USA':35, 'Great Britain':22, 'China':20, 'Germany':13}}

bei=nested_d["Beijing"]["USA"]
lon=nested_d["London"]["USA"]
rio=nested_d["Rio"]["USA"]

US_count.append(bei)
US_count.append(lon)
US_count.append(rio)
print(US_count)

谢谢!

【问题讨论】:

  • US_count = [bei, lon, rio]?!

标签: python-3.x dictionary nested


【解决方案1】:

使用列表推导。我们遍历nested_d 中的键,并为每个键检索'USA' 的值。

print([nested_d[key]['USA'] for key in nested_d])

[36, 46, 35]

注意:这确实假设 'USA' 可用作所有嵌套字典中的键。

【讨论】: