【问题标题】:Return Values on List of Dictionaries [closed]字典列表上的返回值[关闭]
【发布时间】:2021-11-08 06:41:24
【问题描述】:

我有以下字典列表:

voting_data = [ {"county":"Arapahoe", "registered_voters": 422829}, {"county":"Denver", "registered_voters": 463353}, {"county":"Jefferson", "registered_voters": 432438}]

我需要创建一个for循环,执行时会产生以下语句:

“阿拉帕霍县有 422,829 名登记选民”(等等)。

我整天都被困在这个问题上,并尝试了不同的循环/变量。我无法绕过它。我知道我正在寻找检索每个项目的索引值(因此,对于“county”:“Arapahoe”,我正在寻找检索“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")

【问题讨论】:

  • 阅读official Python tutorial。阅读。不要浏览它。这不是 for 循环的工作方式。或者dict.values 是如何工作的。猜测和检查以弄清楚代码是如何工作的是行不通的。在尝试解决实际问题之前,您需要了解该语言。
  • 您的嵌套循环不是必需的,因为您可以使用字典的键访问字典。请检查我的解释,希望它足以指导您如何使用嵌套数据结构。
  • 这能回答你的问题吗? Iterating over dictionaries using 'for' loops

标签: python list dictionary for-loop


【解决方案1】:

您不需要嵌套循环。您需要遍历列表,并访问字典的每个属性:

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

【讨论】:

    【解决方案2】:

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

    希望能阐明为什么您不需要嵌套循环。由于您有一个字典列表,您可以遍历该列表,然后使用其特定键(在本例中为县和注册选民)访问每个字典

    【讨论】:

      【解决方案3】:

      类似下面的东西(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']
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-03-18
        • 2021-01-31
        • 2017-11-01
        • 1970-01-01
        • 2014-01-02
        • 2013-02-18
        相关资源
        最近更新 更多