37

My code is

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

Seems to work fine for printing the values of dictionary keys for index = 0.

But for the life of me I can't figure out how to put this for loop inside a for loop that iterates through the unknown number of dictionaries in dataList

Sнаđошƒаӽ
  • 15,289
  • 12
  • 72
  • 86
C. P. Wagner
  • 401
  • 1
  • 5
  • 5
  • No, please don't use iteration counters unless you absolutely have to. Although it is *a solution* to this problem, it is not the best one. – Hannes Ovrén Mar 08 '16 at 09:55

7 Answers7

91

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.

MSeifert
  • 133,177
  • 32
  • 312
  • 322
10

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.

Avihoo Mamka
  • 4,466
  • 3
  • 29
  • 42
5
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}')
MSeifert
  • 133,177
  • 32
  • 312
  • 322
atufa shireen
  • 161
  • 2
  • 7
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. 

1

"""The approach that offers the most flexibility and just seems more dynamically appropriate to me is as follows:"""

Loop thru list in a Function called.....

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

"""This way, the Datalist can be any format of a Dictionary you throw at it, otherwise you can end up dealing with format issues, I found. Try the following and it will still works......."""

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

Another pythonic solution is using collections module.

Here is an example where I want to generate a dict containing only 'Name' and 'Last Name' values:

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

Output should be:

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

had a similar issue, fixed mine by using a single for loop to iterate over the list, see code snippet

de = {"file_name":"jon","creation_date":"12/05/2022","location":"phc","device":"s3","day":"1","time":"44692.5708703703","year":"1900","amount":"3000","entity":"male"}
se = {"file_name":"bone","creation_date":"13/05/2022","location":"gar","device":"iphone","day":"2","time":"44693.5708703703","year":"2022","amount":"3000","entity":"female"}
re = {"file_name":"cel","creation_date":"12/05/2022","location":"ben car","device":"galaxy","day":"1","time":"44695.5708703703","year":"2022","amount":"3000","entity":"male"}
te = {"file_name":"teiei","creation_date":"13/05/2022","location":"alcon","device":"BB","day":"2","time":"44697.5708703703","year":"2022","amount":"3000","entity":"female"}
ye = {"file_name":"js","creation_date":"12/05/2022","location":"woji","device":"Nokia","day":"1","time":"44699.5708703703","year":"2022","amount":"3000","entity":"male"}
ue = {"file_name":"jsdjd","creation_date":"13/05/2022","location":"town","device":"M4","day":"5","time":"44700.5708703703","year":"2022","amount":"3000","entity":"female"}


d_list = [de,se,re,te,ye,ue]


for dic in d_list:
    print (dic['file_name'],dic['creation_date'])
Willie Cheng
  • 6,537
  • 11
  • 43
  • 63
Belz
  • 1
  • 2
  • 1
    As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community May 11 '22 at 23:57