在 Python 中獲取字典的值
Manav Narula
2023年10月10日
Python
Python Dictionary
在本教程中,我們將學習如何在 Python 中獲取字典的值。
字典的 values() 方法在 dict_values 物件中返回字典值的表示。
例如,
d = {"1": "a", "2": "b", "3": "c", "4": "d"}
print(d.values(), type(d.values()))
輸出:
dict_values(['a', 'b', 'c', 'd']) <class 'dict_values'>
我們將學習如何通過將這個物件轉換為一個列表來獲得一個字典的值。
在 Python 中使用 list() 函式獲取字典的值
list() 函式可用於型別轉換,並將 values() 函式返回的 dict_values 物件轉換為適當的列表。
d = {"1": "a", "2": "b", "3": "c", "4": "d"}
lst = list(d.values())
print(lst)
輸出:
['a', 'b', 'c', 'd']
Python 中使用解包運算子*來獲取字典的值
Python 中的*運算子可用於從可迭代物件中解包元素。我們可以將所有的元素單獨解包到一個新的列表中。
我們可以使用此運算子來獲取列表中字典的所有值。
以下程式碼顯示瞭如何在 Python 中將此運算子與 values() 函式一起使用。
d = {"1": "a", "2": "b", "3": "c", "4": "d"}
lst = [*d.values()]
print(lst)
輸出:
['a', 'b', 'c', 'd']
在 Python 中使用 extend() 函式獲取字典的值
extend() 函式可以接受一個可迭代的物件,並將該物件中的所有元素新增到某些列表的末尾。
我們可以使用它來獲取列表中字典的所有值。該函式可以接受 dict_values() 物件,並將專案新增到某些空列表的末尾。
以下程式碼實現了此邏輯。
d = {"1": "a", "2": "b", "3": "c", "4": "d"}
lst = []
lst.extend(d.values())
print(lst)
輸出:
['a', 'b', 'c', 'd']
現在,在本教程中,我們討論了三種方法。在這三種方法中,就速度而言,list() 函式和*解包運算子被認為是最有效的。對於小型字典,解包運算子*是最快的運算子,而對於大型字典,list() 函式被認為效率更高。
Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe
作者: Manav Narula
Manav is a IT Professional who has a lot of experience as a core developer in many live projects. He is an avid learner who enjoys learning new things and sharing his findings whenever possible.
LinkedIn