如何使用while循环遍历字典中的项目?

Han*_*aka 3 python loops while-loop python-3.x

我知道如何使用 for 循环遍历字典中的项目。但我需要知道如何使用 while 循环遍历字典中的项目。那可能吗?

这就是我用 for 循环尝试的方式。

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


for values,keys in user_info.items():
    print(values, "=", keys)
Run Code Online (Sandbox Code Playgroud)

Nie*_*ano 6

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])
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)

  • “这只是相同的过程”——几乎相同的过程。`for` 循环不会使用 `next()` 的标记值,而是捕获 `StopIteration`。 (3认同)