Iterating Over Dictionaries Using 'For' Loops

Iterating over dictionaries using 'for' loops

key is just a variable name.

for key in d:

will simply loop over the keys in the dictionary, rather than the keys and values. To loop over both key and value you can use the following:

For Python 3.x:

for key, value in d.items():

For Python 2.x:

for key, value in d.iteritems():

To test for yourself, change the word key to poop.

In Python 3.x, iteritems() was replaced with simply items(), which returns a set-like view backed by the dict, like iteritems() but even better.
This is also available in 2.7 as viewitems().

The operation items() will work for both 2 and 3, but in 2 it will return a list of the dictionary's (key, value) pairs, which will not reflect changes to the dict that happen after the items() call. If you want the 2.x behavior in 3.x, you can call list(d.items()).

Iterating over dictionary in Python and using each value

Use for loop for iteration.

dict = {'a': 1, 'b': 2, 'c': 3}
for key, value in dict.items():
print(key+" "+ str(value))

for key in dict:
print(key+ " "+str(dict[key]))

The first one iterates over items and gives you keys and values. The second one iterates over keys and then it is accessing value from the dictionary using the key.

how to iterate over items in dictionary using while loop?

You can iterate the items of a dictionary using iter and next with a while loop. This is almost the same process as how a for loop would perform the iteration in the background on any iterable.

  • https://docs.python.org/3/library/functions.html
  • https://docs.python.org/3/library/stdtypes.html#iterator-types

Code:

user_info = {
"username" : "Hansana123",
"password" : "1234",
"user_id" : 3456,
"reg_date" : "Nov 19"
}

print("Using for loop...")
for key, value in user_info.items():
print(key, "=", value)

print()

print("Using while loop...")
it_dict = iter(user_info.items())
while key_value := next(it_dict, None):
print(key_value[0], "=", key_value[1])

Output:

Using for loop...
username = Hansana123
password = 1234
user_id = 3456
reg_date = Nov 19

Using while loop...
username = Hansana123
password = 1234
user_id = 3456
reg_date = Nov 19

Python 3.5 iterate through a list of dictionaries

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.

How to iterate over a dictionary?

foreach(KeyValuePair<string, string> entry in myDictionary)
{
// do something with entry.Value or entry.Key
}

For Looping Over Dictionary Object

data is a dictionary, not a function, so you shouldn't use parenthesis to attempt to access it.

You should also be iterating over data.items(), not len(range(data)). You're iterating over the keys of a dictionary, not a list.

With these two corrections, we get the following:

for key, values in data.items():
ratio = values[0]/values[1]

Can we use for loop to iterate over a dict of dicts?

In general, no. Dicts can be arbitrarily recursively deep, and there's no good way to traverse them using nothing but a for loop. (You could implement your own stack using a list and simulate recursion, but that's not "good".)

There's some recursive code for traversing dictionaries (counting the depth) in this question.

In specific, sure. Knowing the structure in advance, you can use the right number of for loops:

n = {'key1': {'keya': 'a', 'keyb': 'b'},
'key2': {'key3':{'keyc': 'c'}}, 'key4': 4}

for k1,v1 in n.items():
try:
for k2,v2 in v1.items():
try:
for k3,v3 in v2.items():
print(v3)
except AttributeError:
pass
except AttributeError:
pass

Iterate Over Dictionary

Both are different if remove parenthesis in print because you are using python 2X

desc = {'city': 'Monowi', 'state': 'Nebraska', 'county':'Boyd', 'pop': 1}

for i, j in desc.items():
print i, j

for i in desc.items():
print i

output

county Boyd
city Monowi
state Nebraska
pop 1
('county', 'Boyd')
('city', 'Monowi')
('state', 'Nebraska')
('pop', 1)

Python - Iterate the keys and values from the dictionary

You can use this code snippet.

dictionary= {1:"a", 2:"b", 3:"c"}

#To iterate over the keys
for key in dictionary.keys():
print(key)

#To Iterate over the values
for value in dictionary.values():
print(value)

#To Iterate both the keys and values
for key, value in dictionary.items():
print(key,'\t', value)


Related Topics



Leave a reply



Submit