如何使用while循环遍历字典中的项目?
我知道如何使用 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)
回答
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
- “这只是相同的过程”——几乎相同的过程。`for` 循环不会使用 `next()` 的标记值,而是捕获 `StopIteration`。