转载:http://www.runoob.com/python/python-dictionary.html

dict = {\'Name\':\'Zara\',\'Age\':7,\'Class\':\'First\'}
print(\"dict[\'Name\']:\",dict[\'Name\'])
print(\"dict[\'Age\']:\",dict[\'Age\'])

dict[‘Name’]: Zara
dict[‘Age’]: 7

dict[\'Age\']=8
dict[\'School\']=\'RUNOOB\'
print(dict)

{‘Name’: ‘Zara’, ‘Age’: 8, ‘Class’: ‘First’, ‘School’: ‘RUNOOB’}

del(dict[\'Name\'])
print(dict)

{‘Age’: 8, ‘Class’: ‘First’, ‘School’: ‘RUNOOB’}

builtin function

#如果两个字典的元素相同返回0,如果字典dict1大于字典dict2返回1,如果字典dict1小于字典dict2返回-1。
cmp(dict1, dict2)

len(dict)
str(dict)
type(variable)
dict.clear()
dict.copy()

dict.fromkeys(seq[, val])
#创建一个新字典,以序列 seq 中元素做字典的键,val 为字典所有键对应的初始值

dict.get(key, default=None)
#返回指定键的值,如果值不在字典中返回default值
dict.has_key(key)
#如果键在字典dict里返回true,否则返回false
dict.items()
#以列表返回可遍历的(键, 值) 元组数组
dict = {\'Google\': \'www.google.com\', \'Runoob\': \'www.runoob.com\', \'taobao\': \'www.taobao.com\'}
 
print( \"字典值 : %s\" % dict.items())
for key,values in  dict.items():
    print (key,values)

字典值 : dict_items([(‘Google’, ‘www.google.com’), (‘Runoob’, ‘www.runoob.com’), (‘taobao’, ‘www.taobao.com’)])
Google www.google.com
Runoob www.runoob.com
taobao www.taobao.com

dict.keys()
#以列表返回一个字典所有的键
dict.values()
#以列表返回字典中的所有值
dict.setdefault(key, default=None)
#和get()类似, 但如果键不存在于字典中,将会添加键并将值设为defaul
dict.update(dict2)
#把字典dict2的键/值对更新到dict里
pop(key[,default])
#删除字典给定键 key 所对应的值,返回值为被删除的值。key值必须给出。 否则,返回default值。
popitem()
#随机返回并删除字典中的一对键和值。
收藏 打印