【问题标题】:How to iterate a list of dictionary with python3如何用python3迭代字典列表
【发布时间】:2019-09-22 15:42:06
【问题描述】:

遍历字典结果列表错误:

AttributeError: 'list' 对象没有属性 'items'

变化:

for the_key, the_value in bucket.items():

到:

for the_key, the_value in bucket[0].items():

结果是第一个元素。我想捕获所有元素

bucket = [{'Name:': 'Share-1', 'Region': 'ap-south-1'}, {'Name:': 'Share-2', 'Region': 'us-west-1'}]


for the_key, the_value in bucket.items():
    print(the_key, 'corresponds to', the_value)

实际结果:

AttributeError: 'list' 对象没有属性 'items'

想要的输出:

Name: Share-1
Region: ap-south-1

Name: Share-2
Region: us-west-1

【问题讨论】:

    标签: python python-3.x list loops dictionary


    【解决方案1】:

    因为bucket是一个列表,而不是dict,所以你应该先迭代它,对于每个dict,迭代它的items

    bucket = [{'Name:': 'Share-1', 'Region': 'ap-south-1'}, {'Name:': 'Share-2', 'Region': 'us-west-1'}]
    
    for d in bucket:
        for the_key, the_value in d.items():
            print(the_key, 'corresponds to', the_value)
    

    输出:

    Name: corresponds to Share-1
    Region corresponds to ap-south-1
    Name: corresponds to Share-2
    Region corresponds to us-west-1
    

    【讨论】:

      【解决方案2】:

      你的数据有两层,所以你需要两个循环:

      for dct in lst:
          for key, value in dct.items():
              print(f"{key}: {value}")
          print() # empty line between dicts
      

      【讨论】:

        【解决方案3】:

        可以用更functional 的方式来做,我更喜欢它:

        map(lambda x: print("name: {x}".format(x=x['Name:'])), bucket)
        

        它很懒,没有for 循环,而且可读性更强

        运行时间:

        bucket = [{'Name:': 'Share-1', 'Region': 'ap-south-1'}, 
                  {'Name:': 'Share-2', 'Region': 'us-west-1'}]
        

        你会得到(当然你需要消耗map):

        name: Share-1
        name: Share-2
        

        【讨论】:

          【解决方案4】:

          你可以试试这个:

          for dictionary in bucket:
              for key, val in dictionary.items():
                  print(the_key, 'corresponds to', the_value) 
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2016-07-19
            • 1970-01-01
            • 2013-07-01
            相关资源
            最近更新 更多