返回字典列表上的值

2024-10-02 20:39:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下词典列表:

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")

Tags: in列表fordatadict词典valuesvoting
3条回答

您可以使用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.    

NOTE:'{:,}'.format(100000) results in formatting the number as 100,000 and returns a string which can be printed in the format you are looking for.


理解嵌套数据结构的行为非常重要。可以使用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_选民)

类似下面的内容(1行)

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']

您不需要嵌套循环。您需要在列表上循环,并访问dict的每个属性:

for vd in voting_data:
    print(f'{vd["county"]} has {vd["registered_voters"]} registered voters')

相关问题 更多 >