how to iterate over items in dictionary using while loop?

Viewed 2698

i know how to iterate over items in dictionary using for loop. but i need know is how to iterate over items in dictionary using while loop. is that possible?

This how i tried it with for loop.

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


for values,keys in user_info.items():
    print(values, "=", keys)
3 Answers

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.

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

this is not perfect solution which I did but it is in while loop

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

i = 0
length = len(list(user_info.items()))
keys, values = list(user_info.keys()), list(user_info.values())

while i < length:
    print(values[i], "=", keys[i])
    i += 1

You can't iterate over dict using while loop if acessing while loop because dict elements are unordered and in a while loop you can only access on iterables like str list tuples only by index and dict have no indexes. I hope it will clarify your Question.

Related