我有以下词典列表:
voting_data = [ {"county":"Arapahoe", "registered_voters": 422829}, {"county":"Denver", "registered_voters": 463353}, {"county":"Jefferson", "registered_voters": 432438}]
我需要创建一个for循环,该循环在执行时将生成以下语句:
“阿拉帕霍县有422829名登记选民”(等等)
我一整天都在做这个,并且尝试了不同的循环/变量。我不能把我的头绕在它周围。我知道我希望检索每个项目的索引值(因此,对于“县”:“Arapahoe”,我希望检索“Arapahoe”和“登记选民”:422829,“422829”)
最近,我提出了:
for counties_dict in voting_data:
for i in counties_dict.values("county") and j in counties_dict.values("registered_voters"):
print(f" {i} county has {j:,} registered voters")
您可以使用
dict.get()
来获取特定键的值理解嵌套数据结构的行为非常重要。可以使用
for-loop
在对象列表上迭代在本例中,项目是字典。为了访问字典(键、值对),您可以直接从相应的键访问值
如果您想迭代字典(键和值对),则需要额外的for循环
希望这能澄清为什么在您的案例中不需要嵌套循环。因为您有一个字典列表,所以可以遍历该列表,然后使用每个字典的特定键访问每个字典(在本例中是county和registered_选民)
类似下面的内容(1行)
输出
您不需要嵌套循环。您需要在列表上循环,并访问dict的每个属性:
相关问题 更多 >
编程相关推荐