D = { 'food': 'Spam', 'quantity': 4, 'color': 'pink' }
或者:python
D = {} D['food'] = 'Spam' D['quantity'] = 4
或者(這種方式下鍵必須是字符串):函數
>>> D = dict(name='bob', age=20) >>> D {'age': 20, 'name': 'bob'}
嵌套spa
res = { 'name': {'first': 'Bob', 'last': 'Smith'}, 'job': ['dev', 'mgr'], 'age': 40.5 } print(res) print(res['name']['first'])
D['food']
D['quantity'] += 1
for k in res.keys(): print(k, res[k])
>>> D = {'spam': 2, 'ham': 1, 'eggs': 3} >>> for it in D.items(): ... print(it[0], it[1]) ... ('eggs', 3) ('ham', 1) ('spam', 2)
m = { 'a': 'A', 'b': 'B' } for (key, value) in m.items(): print(key, '=>', value)
訪問不存在的鍵將會報錯。code
if 'name' in res: print("has name") if not 'a' in res: print("hasn't a")
或者使用帶默認值的get:對象
v = res.get('a', 0)
或者經過if-else:排序
v = res['a'] if 'a' in res else 0
>>> D1 = {'a':1, 'b':2} >>> D2 = {'a':3, 'c':4} >>> D1.update(D2) >>> D1 {'a': 3, 'c': 4, 'b': 2} >>> D2 {'a': 3, 'c': 4}
m = {"a": 1, "c": 2, "b": 3} items = m.items() items.sort() print m # {'a': 1, 'c': 2, 'b': 3} print items # [('a', 1), ('b', 3), ('c', 2)]
import operator t = {"a":1, "c":2, "b":3} sorted(t.iteritems(), key=operator.itemgetter(1), reverse=True) # 輸出(按value由大到小排序),注意這是元組的列表 [('b', 3), ('c', 2), ('a', 1)]
iteritems()
返回一個迭代器,遍歷字典的全部元素字符串
operator.itemgetter(1)
返回一個函數,這個函數接收一個列表,而且返回第1個元素,若是傳入0就是按key排序了。get
字符集合:it
>>> x = set('abcde') >>> x set(['a', 'c', 'b', 'e', 'd'])
x = set('abcde') y = set('bdxyz') print('e' in x) # True print(x - y) # set(['a', 'c', 'e']) print(x | y) # set(['a', 'c', 'b', 'e', 'd', 'y', 'x', 'z']) print(x & y) # set(['b', 'd']) print(x ^ y) # set(['a', 'c', 'e', 'y', 'x', 'z']) print(x > y, x < y) # (False, False)