简体   繁体   中英

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)

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

input<\/strong>

a = ["AB", "corona"]
b = ["india",'openVINO']
c = ["korea"]
d = ["26", "10.mp3", "Nvidia.mp4"]
e = ["washington DC",6]
f = ['swiss']

import itertools

lst = [a,b,c,d,e,f]
# print(lst)
lsts = list(itertools.product(*lst))
for lst in lsts:
  print('\n')
  for con in lst:
    print(con)

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM