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