【问题标题】:Python 3.5 iterate through a list of dictionariesPython 3.5 遍历字典列表
【发布时间】:2016-06-22 04:47:24
【问题描述】:

我的代码是

index = 0
for key in dataList[index]:
    print(dataList[index][key])

似乎可以很好地打印索引 = 0 的字典键的值。

但是对于我的生活,我无法弄清楚如何将这个 for 循环放在一个 for 循环中,该循环遍历 dataList 中未知数量的字典

【问题讨论】:

  • 不,除非绝对必要,否则请不要使用迭代计数器。虽然它是解决这个问题的一种解决方案,但它并不是最好的。

标签: python list for-loop dictionary python-3.5


【解决方案1】:

另一个pythonic解决方案是使用collections module

这是一个示例,我想生成一个仅包含“姓名”和“姓氏”值的字典:

from collections import defaultdict

test_dict = [{'Name': 'Maria', 'Last Name': 'Bezerra', 'Age': 31},
             {'Name': 'Ana', 'Last Name': 'Mota', 'Age': 31},
             {'Name': 'Gabi', 'Last Name': 'Santana', 'Age': 31}]

collect = defaultdict(dict)

# at this moment, 'key' becomes every dict of your list of dict
for key in test_dict:
    collect[key['Name']] = key['Last Name']

print(dict(collect))

输出应该是:

{'Name': 'Maria', 'Last Name': 'Bezerra'}, {'Name': 'Ana', 'Last Name': 'Mota'}, {'Name': 'Gabi', 'Last Name': 'Santana'}

【讨论】:

    【解决方案2】:

    """提供最大灵活性并且对我来说似乎更动态的方法如下:"""

    在名为.....的函数中循环列表

    def extract_fullnames_as_string(list_of_dictionaries):
    
        result = ([val for dic in list_of_dictionaries for val in 
        dic.values()])
    
        return ('My Dictionary List is ='result)
    
    
        dataList = [{'first': 3, 'last': 4}, {'first': 5, 'last': 7},{'first': 
        15, 'last': 9},{'first': 51, 'last': 71},{'first': 53, 'last': 79}]
        
        print(extract_fullnames_as_string(dataList))
    

    """这样,Datalist 可以是任何格式的字典,我发现,否则你最终会处理格式问题。试试下面的方法,它仍然可以工作...... ."""

        dataList1 = [{'a': 1}, {'b': 3}, {'c': 5}]
        dataList2 = [{'first': 'Zhibekchach', 'last': 'Myrzaeva'}, {'first': 
        'Gulbara', 'last': 'Zholdoshova'}]
    
        print(extract_fullnames_as_string(dataList1))
        print(extract_fullnames_as_string(dataList2))
    

    【讨论】:

      【解决方案3】:
      def extract_fullnames_as_string(list_of_dictionaries):
          
      return list(map(lambda e : "{} {}".format(e['first'],e['last']),list_of_dictionaries))
      
      
      names = [{'first': 'Zhibekchach', 'last': 'Myrzaeva'}, {'first': 'Gulbara', 'last': 'Zholdoshova'}]
      print(extract_fullnames_as_string(names))
      
      #Well...the shortest way (1 line only) in Python to extract data from the list of dictionaries is using lambda form and map together. 
      
      

      【讨论】:

      • 只需将 lambda 与 map 一起使用
      【解决方案4】:
      use=[{'id': 29207858, 'isbn': '1632168146', 'isbn13': '9781632168146', 'ratings_count': 0}]
      for dic in use:
          for val,cal in dic.items():
              print(f'{val} is {cal}')
      

      【讨论】:

        【解决方案5】:

        您可以只遍历您的listlenrange 的索引:

        dataList = [{'a': 1}, {'b': 3}, {'c': 5}]
        for index in range(len(dataList)):
            for key in dataList[index]:
                print(dataList[index][key])
        

        或者您可以使用带有 index 计数器的 while 循环:

        dataList = [{'a': 1}, {'b': 3}, {'c': 5}]
        index = 0
        while index < len(dataList):
            for key in dataList[index]:
                print(dataList[index][key])
            index += 1
        

        您甚至可以直接遍历列表中的元素:

        dataList = [{'a': 1}, {'b': 3}, {'c': 5}]
        for dic in dataList:
            for key in dic:
                print(dic[key])
        

        只需遍历字典的值,甚至可以不进行任何查找:

        dataList = [{'a': 1}, {'b': 3}, {'c': 5}]
        for dic in dataList:
            for val in dic.values():
                print(val)
        

        或者将迭代包装在列表理解或生成器中,稍后再解包:

        dataList = [{'a': 1}, {'b': 3}, {'c': 5}]
        print(*[val for dic in dataList for val in dic.values()], sep='\n')
        

        可能性无穷无尽。你喜欢什么是一个选择问题。

        【讨论】:

          【解决方案6】:

          您可以轻松做到这一点:

          for dict_item in dataList:
            for key in dict_item:
              print dict_item[key]
          

          它将遍历列表,并且对于列表中的每个字典,它将遍历键并打印其值。

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2019-11-29
            相关资源
            最近更新 更多