Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to iterate over items in dictionary using while loop?

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)
like image 364
Hansana Prabath Avatar asked Sep 12 '25 01:09

Hansana Prabath


2 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.

  • 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
like image 175
Niel Godfrey Ponciano Avatar answered Sep 13 '25 16:09

Niel Godfrey Ponciano


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

like image 31
Tofiq Avatar answered Sep 13 '25 16:09

Tofiq