Python中字典及遍歷常用函數(shù)的使用詳解
字典中元素的個數(shù)計算
len(字典名)
舉例:
person={"姓名":"張三","年齡":20,"性別":"男"}
print(len(person))
輸出:
3
字典中的鍵名
字典名.keys()
舉例:
person={"姓名":"張三","年齡":20,"性別":"男"}
print(person.keys())
persons=person.keys()
print(type(persons))
輸出:
dict_keys(['姓名', '年齡', '性別'])
<class 'dict_keys'>
加粗樣式字典中的鍵值
字典名.values()
舉例:
person={"姓名":"張三","年齡":20,"性別":"男"}
print(person.values())
persons=person.values()
print(type(persons))
輸出:
dict_values(['張三', 20, '男'])
<class 'dict_values'>
字典的鍵名以及對應的鍵值
字典名.items()
person={"姓名":"張三","年齡":20,"性別":"男"}
print(person.items())
persons=person.items()
print(type(persons))
輸出:
dict_items([('姓名', '張三'), ('年齡', 20), ('性別', '男')])
<class 'dict_items'>
字典的遍歷
鍵名,鍵值,鍵名對應鍵值的遍歷。
方法一
舉例:
person={"姓名":"張三","年齡":20,"性別":"男"}
persons_1=person.keys()
persons_2=person.values()
persons_3=person.items()
for a in persons_1://鍵名的遍歷
print(a,end=' ')
print("\n")
for b in persons_2://鍵值的遍歷
print(b,end=' ')
print("\n")
for c in persons_3://鍵名與對應的鍵值的遍歷
print(c,end=' ')
輸出:
姓名 年齡 性別
張三 20 男
('姓名', '張三') ('年齡', 20) ('性別', '男')
方法二
person={"姓名":"張三","年齡":20,"性別":"男"}
for keys in person.keys()://鍵名的遍歷
print(keys,end=' ')
print("\n")
for values in person.values()://鍵值的遍歷
print(values,end=' ')
print("\n")
for key,values in person.items()://鍵名與對應的鍵值的遍歷
print(key,values)
輸出:
姓名 年齡 性別
張三 20 男
姓名 張三
年齡 20
性別 男
到此這篇關于Python中字典及遍歷常用函數(shù)的使用詳解的文章就介紹到這了,更多相關Python字典遍歷內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Python文本統(tǒng)計功能之西游記用字統(tǒng)計操作示例
這篇文章主要介紹了Python文本統(tǒng)計功能之西游記用字統(tǒng)計操作,結(jié)合實例形式分析了Python文本讀取、遍歷、統(tǒng)計等相關操作技巧,需要的朋友可以參考下2018-05-05
python使用zip將list轉(zhuǎn)為json的方法
今天小編就為大家分享一篇python使用zip將list轉(zhuǎn)為json的方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-12-12
一文詳解如何在Python中實現(xiàn)switch語句
這篇文章主要給大家介紹了關于如何在Python中實現(xiàn)switch語句的相關資料,今天在學習python的過程中,發(fā)現(xiàn)python沒有switch這個語法,所以這里給大家總結(jié)下,需要的朋友可以參考下2023-09-09
Python常見庫matplotlib學習筆記之畫圖文字的中文顯示
在Python中使用matplotlib或者plotnine模塊繪圖時,常常出現(xiàn)圖表中無法正常顯示中文的問題,下面這篇文章主要給大家介紹了關于Python常見庫matplotlib學習筆記之畫圖文字的中文顯示的相關資料,需要的朋友可以參考下2023-05-05
簡單了解Django ContentType內(nèi)置組件
這篇文章主要介紹了簡單了解Django ContentType內(nèi)置組件,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下2019-07-07

