Python3 字典(Dictionary)
Python3 字典(Dictionary)
字典是一個無序、可變和有索引的集合。它是一種可變?nèi)萜髂P?,而且可存儲任意類型對象?/p>
1. 字典的定義
在 Python 中,字典用花括號編寫,擁有鍵和值。
字典的每個鍵值 key=>value 對用冒號 : 分割,每個對之間用逗號(,)分割,整個字典包括在花括號 {} 中 ,格式如下所示:
d = {key1 : value1, key2 : value2, key3 : value3 }
鍵必須是唯一的,但值則不必。
值可以取任何數(shù)據(jù)類型,但鍵必須是不可變的,如字符串,數(shù)字。
一個簡單的字典范例:
dict = {'name': 'yapf', 'likes': 123, 'url': 'www.aalaour.cn'}
也可如此創(chuàng)建字典:
dict1 = { 'abc': 456 } dict2 = { 'abc': 123, 98.6: 37 }
2. 訪問字典元素
把相應(yīng)的鍵放入到方括號中,如下范例:
Python3 范例
#!/usr/bin/python3 dict = {'Name': 'yapf', 'Age': 7, 'Class': 'First'}
print ("dict['Name']: ", dict['Name']) print ("dict['Age']: ", dict['Age'])
相關(guān)文章
- Python 中文編碼
- Python 列表 List
- Python 日期和時間
- Python 高級鏈表
- Python 二叉樹
- Python 回溯
- Python3 運算符
- Python3 XML 解析
- Python3 JSON 解析
- Python log() 函數(shù)
- Python File readlines() 方法
- Python os.chown() 方法
- Python os.mkdir() 方法
- Python os.rename() 方法
- Python os.renames() 方法
- Python os.symlink() 方法
- Python decode()方法
- Python isspace()方法
- Python ljust()方法
- Python time mktime()方法