The dictionary is the only type of mapping in Python. Dictionaries are mutable, unordered, variable-sized key-value mappings, sometimes called hash lists or associative arrays.
Examples are below:
DiC = {"Apple": 2, "orange":1} #定义一个字典
>>> dic.copy () #复制字典
{' Orange ': 1, ' Apple ': 2}
>>> dic["banana"] = 5 #增加一项
>>> dic.items () #获得字典中成员的列表
[(' Orange ', 1), (' Apple ', 2), (' Banana ', 5)]
>>> dic.pop ("Apple", 3) #删除 "Apple", if not Apple, returns 3
3
>>> dic
{' Orange ': 1, ' Banana ': 5}
>>> Dic.keys () #获得键的列表
[' Orange ', ' banana ']
>>> dic.values () # Get a worthwhile list
[1, 5]
>>> dic.update ({"Banana": 3}) #更新 "Banana" value
>>> dic
{ ' Orange ': 1, ' Banana ': 3}
>>> dic.update ({"Apple": 2}) #更新 "Apple" value, if not, Add
>>> dic
{' Orange ': 1, ' Apple ': 2, ' Banana ': 3}
>>> dic["Orange"] #通过键获取值
1
>>> dic.clear () #清空字典
>>> DIC
{}
Look at one more of the following:
#创建一个初始字典, it contains a string and an integer. Their keys are all strings.
>>> book = {"title": "Python Web Development", "Year": 2008}
#显示这个对象.
>>> Book
{' Year ': +, ' title ': ' Python Web Development '}
#检查字典是否含有某个键, for Real.
>>> ' year ' in book
True
#检查字典是否含有某个键, for the false
>>> "Pub" in the book
False
#使用get方法获取给定键的值 (the default value is obtained here)
>>> Book.get ("Pub", "N/A")
' N/A '
#加入一个新的键-value pairs
>>> book["Pub"] = "Addison Wesley"
#再次使用get方法, but the success of this one gets the value
>>> Book.get ("Pub", "N/A")
' Addison Wesley '
#迭代整个字典并显示每一对键-Value
>>> for key in book:
Print key, ":", Book[key]
year:2008
Pub:addison Wesley
Title:python Web Development
Common methods in dictionaries:
Dic.clear (): Empty dictionary
Dic.copy (): Copy dictionary
Dic.get (k): Gets the value of the key K
Dic.has_key (k): Contains key K
Dic.items (): Get a list of keys and values
Dic.keys (): Get a list of keys
Dic.pop (k): Delete key k
Dic.update (): Update member (update dictionary with another dictionary)
Dic.values (): Get a list of values
Python: The basic operation of a dictionary