溫馨提示×

python遍歷字典的方法是什么

小億
84
2024-02-01 16:56:53
欄目: 編程語言

在Python中,可以使用for循環(huán)來遍歷字典。有幾種常用的方法可以遍歷字典的鍵、值或鍵值對:

  1. 遍歷字典的鍵:
my_dict = {"a": 1, "b": 2, "c": 3}
for key in my_dict:
    print(key)

輸出:

a
b
c
  1. 遍歷字典的值:
my_dict = {"a": 1, "b": 2, "c": 3}
for value in my_dict.values():
    print(value)

輸出:

1
2
3
  1. 遍歷字典的鍵值對:
my_dict = {"a": 1, "b": 2, "c": 3}
for key, value in my_dict.items():
    print(key, value)

輸出:

a 1
b 2
c 3

還可以使用內(nèi)置的iter()函數(shù)結(jié)合next()函數(shù)遍歷字典的鍵或值:

my_dict = {"a": 1, "b": 2, "c": 3}
my_dict_iter = iter(my_dict)

# 遍歷字典的鍵
while True:
    try:
        key = next(my_dict_iter)
        print(key)
    except StopIteration:
        break

# 遍歷字典的值
my_dict_iter = iter(my_dict.values())
while True:
    try:
        value = next(my_dict_iter)
        print(value)
    except StopIteration:
        break

輸出:

a
b
c
1
2
3

以上是遍歷字典的幾種常見方法,根據(jù)具體情況選擇合適的方法進(jìn)行遍歷。

0