Python 訪問字典(dictionary)中元素


 

訪問python字典中元素的幾種方式

 

一:通過“鍵值對”(key-value)訪問:

 print(dict[key])

dict = {1: 1, 2: 'aa', 'D': 'ee', 'Ty': 45}
print(dict['D'])

輸出:
ee

 

dict.get(key,[default]) :default為可選項,用於指定當‘鍵’不存在時 返回一個默認值,如果省略,默認返回None

dict = {1: 1, 2: 'aa', 'D': 'ee', 'Ty': 45}
print(dict.get(2))
print(dict.get(3))
print(dict.get(4, ['字典中不存在鍵為4的元素']))

輸出:
aa
None
['字典中不存在鍵為4的元素']

 

二:遍歷字典:

1.使用字典對象的dict.items()方法獲取字典的各個元素即“鍵值對”的元祖列表:

dict = {1: 1, 2: 'aa', 'D': 'ee', 'Ty': 45}
for item in dict.items():
    print(item)

輸出:
(1, 1)
(2, 'aa')
('D', 'ee')
('Ty', 45)

 

2.獲取到具體的每個鍵和值:

dict = {1: 1, 2: 'aa', 'D': 'ee', 'Ty': 45}
for key, value in dict.items():
    print(key, value)

輸出:
1 1
2 aa
D ee
Ty 45

 

3.還可以使用keys()和values()方法獲取字典的鍵和值列表:

dict = {1: 1, 2: 'aa', 'D': 'ee', 'Ty': 45}
for key in dict.keys():
    print(key)
for value in dict.values(): print(value) 輸出: 1 2 D Ty
1 aa ee 45

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM