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'>
字典的鍵名以及對應(yīng)的鍵值
字典名.items()
person={"姓名":"張三","年齡":20,"性別":"男"} print(person.items()) persons=person.items() print(type(persons))
輸出:
dict_items([('姓名', '張三'), ('年齡', 20), ('性別', '男')])
<class 'dict_items'>
字典的遍歷
鍵名,鍵值,鍵名對應(yīng)鍵值的遍歷。
方法一
舉例:
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://鍵名與對應(yīng)的鍵值的遍歷 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()://鍵名與對應(yīng)的鍵值的遍歷 print(key,values)
輸出:
姓名 年齡 性別
張三 20 男
姓名 張三
年齡 20
性別 男
到此這篇關(guān)于Python中字典及遍歷常用函數(shù)的使用詳解的文章就介紹到這了,更多相關(guān)Python字典遍歷內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
詳解利用Pandas求解兩個DataFrame的差集,交集,并集
這篇文章主要和大家講解一下如何利用Pandas函數(shù)求解兩個DataFrame的差集、交集、并集,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以了解一下2022-07-07python?DataFrame數(shù)據(jù)分組統(tǒng)計groupby()函數(shù)的使用
在python的DataFrame中對數(shù)據(jù)進行分組統(tǒng)計主要使用groupby()函數(shù),本文主要介紹了python?DataFrame數(shù)據(jù)分組統(tǒng)計groupby()函數(shù)的使用,具有一定的參考價值,感興趣的可以了解一下2022-03-03python遞歸&迭代方法實現(xiàn)鏈表反轉(zhuǎn)
這篇文章主要介紹了python遞歸&迭代方法實現(xiàn)鏈表反轉(zhuǎn),文章分享一段詳細(xì)實現(xiàn)代碼,需要的小伙伴可以參考一下,希望對你的學(xué)習(xí)或工作有所幫助2022-02-02pycharm最新免費激活碼至2099年(21.3.18親測可用)
這篇文章主要介紹了pycharm最新的激活碼及激活碼的使用方法,幫助大家更好的利用pycharm學(xué)習(xí)python,感興趣的朋友可以了解下。2021-03-03