Python 3.5 iterate through a list of dictionaries

前端 未结 4 1253
深忆病人
深忆病人 2020-12-23 10:34

My code is

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

Seems to work fine for printing the values of dictionary k

相关标签:
4条回答
  • 2020-12-23 10:50
    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. 
    
    
    0 讨论(0)
  • 2020-12-23 10:51
    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}')
    
    0 讨论(0)
  • 2020-12-23 11:06

    You can easily do this:

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

    It will iterate over the list, and for each dictionary in the list, it will iterate over the keys and print its values.

    0 讨论(0)
  • 2020-12-23 11:16

    You could just iterate over the indices of the range of the len of your list:

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

    or you could use a while loop with an index counter:

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

    you could even just iterate over the elements in the list directly:

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

    It could be even without any lookups by just iterating over the values of the dictionaries:

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

    Or wrap the iterations inside a list-comprehension or a generator and unpack them later:

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

    the possibilities are endless. It's a matter of choice what you prefer.

    0 讨论(0)
提交回复
热议问题