我有以下字典列表:
voting_data = [ {"county":"Arapahoe", "registered_voters": 422829}, {"county":"Denver", "registered_voters": 463353}, {"county":"Jefferson", "registered_voters": 432438}]
我需要创建一个for循环,当执行时,将产生以下句子:
阿拉帕霍县有422,829名登记选民;(以此类推)。
我已经被困了一整天,并尝试了不同的循环/变量。我不明白这是怎么回事。我知道我正在寻找检索每个项目的索引值(因此,对于" country "; "Arapahoe"我想找回"阿拉帕霍"。和"registered_voters": 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")
不需要嵌套循环。您需要遍历列表,并访问字典的每个属性:
for vd in voting_data:
print(f'{vd["county"]} has {vd["registered_voters"]} registered voters')
您可以对dict.get()
执行此操作以获取特定键的值。
for d in voting_data:
county = d.get('county')
voters = '{:,}'.format(d.get('registered_voters'))
print(f'{county} county has {voters} registered voters.')
Arapahoe county has 422,829 registered voters.
Denver county has 463,353 registered voters.
Jefferson county has 432,438 registered voters.
注意:
'{:,}'.format(100000)
的结果是将数字格式化为100,000
,并返回一个字符串,该字符串可以以您正在寻找的格式打印。
理解嵌套数据结构的行为是很重要的。您可以使用for-loop
for item in list:
print(item)
在本例中,项是字典。为了访问字典(键、值对),您可以直接从对应的键访问值。
d = {'k1':'v1',
'k2':'v2'}
>>> d['k1']
v1
#OR
>>> d.get('k1')
v1
如果你想迭代字典(键和值对),那么你需要一个额外的for循环.
for k,v in d.items():
print(k, v)
(k1,v1)
(k2,v2)
希望这能澄清为什么你不需要嵌套循环。由于您有一个字典列表,因此可以遍历该列表,然后使用其特定键(在本例中是county和registered_voters)访问每个字典
类似如下(1 line)
voting_data = [ {"county":"Arapahoe", "registered_voters": 422829}, {"county":"Denver", "registered_voters": 463353}, {"county":"Jefferson", "registered_voters": 432438}]
output = [f'{x["county"]} County has {x["registered_voters"]:,} registered voters' for x in voting_data]
print(output)
输出['Arapahoe County has 422,829 registered voters', 'Denver County has 463,353 registered voters', 'Jefferson County has 432,438 registered voters']