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
In Python, to iterate the dictionary ( dict ) with a for loop, use keys() , values() , items() methods. You can also get a list of all keys and values in the dictionary with those methods and list() . Use the following dictionary as an example. You can iterate keys by using the dictionary object directly in a for loop.
Python Iterate Through Dictionary. You can iterate through a Python dictionary using the keys(), items(), and values() methods. keys() returns an iterable list of dictionary keys. items() returns the key-value pairs in a dictionary.
You can loop through a dictionary by using a for loop. When looping through a dictionary, the return value are the keys of the dictionary, but there are methods to return the values as well.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With