字典是无序的
value可以是任意的数据对象,key必须是唯一的,必须是可hash的,大多数情况以数字和字符串的方式构成
--常见方法
查询/访问 get,[]
初始化/赋值 =,setdefault,fromkeys,zip,dict(),copy()
修改/更新 =,update
排序 sorted,sort()
删除 pop,popitem,clear,del
遍历
for key in d/d.iterkeys()/d.keys()/iter(d):
for key,val in d.items()/d.viewitems():
for val in d.values()/d.viewvalues():
--初始化
>>> a={}
>>> a=dict()
>>> b=dict(zip(['name','age'],['qiz',20]))
>>> b
{'age': 20, 'name': 'qiz'}
>>> b=dict(name='qiz',age=20)
>>> b=dict((['name','qiz'],['age',20]))
>>> bb=b.fromkeys(['first_name','last_name'],'chen')
{'first_name': 'chen', 'last_name': 'chen'}
>>> bb=b.fromkeys(['first_name','last_name'])
>>> bb
{'first_name': None, 'last_name': None}
fromkeys(listkeys,default) 把listkeys中的元素作为key均赋值为value,默认为None
>>> d1
{'age': 20, 'sex': 'male'}
>>> d2
{'a': 1, 'b': 2}
>>> d2=d1.copy()
>>> d2
{'age': 20, 'sex': 'male'}
--访问字典
get方法与直接使用key的区别在于
如果没有对应的key值,那么get方法会返回预定的值;
如果存在对应的key值,那么get方法会返回value值;
>>> a={'name':'qiz','age':31,'info':{'addr':'beijing'}}
>>> a['info']['addr']
'beijing'
>>> a.get('info').get('addr')
'beijing'
>>> b={'a': 'apple', 'b': 'banana', 'o': 'orange', 'g': 'grape'}
>>> b['c']
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'c'
>>> b.get('c','not exists')
'not exists'
>>> b.get('o','not exists')
'orange'
--setdefault(key[, default])
If key is in the dictionary, return its value. If not, insert key with a value of default and return default. default defaults to None.
如果key在字典中,则返回其value,如果不在,则以default为value插入对应的key并返回,如果不指定default则缺省为None
--增加,删除,修改
>>> b = {"a" : "apple", "b" : "banana", "g" : "grape", "o" : "orange"}
>>> b["w"] = "watermelon"
>>> b
{'a': 'apple', 'w': 'watermelon', 'b': 'banana', 'o': 'orange', 'g': 'grape'}
>>> del(b["a"])
>>> b["g"] = "grapefruit"
>>> b
{'w': 'watermelon', 'b': 'banana', 'o': 'orange', 'g': 'grape'}
>>> b.pop("b")
banana
>>> b.pop("x")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'x'
>>> b.pop("x",-1)
-1
>>> b
{'w': 'watermelon', 'o': 'orange', 'g': 'grape'}
>>> b.popitem()
('o', 'orange')
>>> b.clear()
>>> b
{}
update的参数可以是以下几种情况:
--字典
--由二元组构成的可迭代对象
--关键字参数
>>> b1
{'a': 'apple', 'b': 'banana'}
>>> b2
{'b': 'bob', 'd': 'dog'}
>>> b1.update(b2)
>>> b1
{'a': 'apple', 'b': 'bob', 'd': 'dog'}
>> b1.update([('e','eye'),('f','frog')])
>> b1.update(c='cat')
--defaultdict
from collections import defaultdict
>>> d=defaultdict(list)
>>> d['root']=3
>>> d
defaultdict(<class 'list'>, {'root': 3})
>>> d['branch'].append(1)
>>> d['branch'].append(2)
>>> d
defaultdict(<class 'list'>, {'branch': [1, 2], 'root': 3})
--遍历
>>> b = {"a" : "apple", "b" : "banana", "g" : "grape", "o" : "orange"}
>>> for k in b:
... print("b[%s]=" % k,b[k])
...
b[b]= banana
b[a]= apple
b[g]= grape
b[o]= orange
>>> print(b.keys())
dict_keys(['b', 'a', 'g', 'o'])
>>> print(b.values())
dict_values(['banana', 'apple', 'grape', 'orange'])
>>> print(b.items())
dict_items([('b', 'banana'), ('a', 'apple'), ('g', 'grape'), ('o', 'orange')])
>>> for (k,v) in b.items():
... print("b[%s] =" % k, v)
...
b[b] = banana
b[a] = apple
b[g] = grape
b[o] = orange
--排序
>>> c
{'a': 'apple', 'c': 'clob', 'b': 'banana'}
>>> sorted(c)
['a', 'b', 'c']
>>> c
{'a': 'apple', 'c': 'clob', 'b': 'banana'}
>>> c={'a': 'apple', 'c': 'clob', 'b': 'banana'}
>>>
>>> for k in sorted(c):
... print(k,c[k])
...
>>> kc=list(c)
>>> kc.sort()
>>> for k in kc:
... print k,c[k]
>>> sorted(c.items(), key=lambda x: x[1])
--OrderedDict
保持插入顺序
>>> from collections import OrderedDict
>>> d = OrderedDict()
>>> d['foo'] = 1
>>> d['bar'] = 2
>>> d['spam'] = 3
>>> d['grok'] = 4
>>> d
OrderedDict([('foo', 1), ('bar', 2), ('spam', 3), ('grok', 4)])
>>> import json
>>> json.dumps(d)
'{"foo": 1, "bar": 2, "spam": 3, "grok": 4}'
--字典方法
| clear(...)
| D.clear() -> None. Remove all items from D.
|
| copy(...)
| D.copy() -> a shallow copy of D
|
| fromkeys(iterable, value=None, /) from builtins.type
| Returns a new dict with keys from iterable and values equal to value.
|
| get(...)
| D.get(k[,d]) -> D[k] if k in D, else d. d defaults to None.
|
| items(...)
| D.items() -> a set-like object providing a view on D's items
|
| keys(...)
| D.keys() -> a set-like object providing a view on D's keys
|
| pop(...)
| D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
| If key is not found, d is returned if given, otherwise KeyError is raised
|
| popitem(...)
| D.popitem() -> (k, v), remove and return some (key, value) pair as a
| 2-tuple; but raise KeyError if D is empty.
|
| setdefault(...)
| D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D
|
| update(...)
| D.update([E, ]**F) -> None. Update D from dict/iterable E and F.
| If E is present and has a .keys() method, then does: for k in E: D[k] = E[k]
| If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v
| In either case, this is followed by: for k in F: D[k] = F[k]
|
| values(...)
| D.values() -> an object providing a view on D's values
来源:https://www.cnblogs.com/adba/p/5711624.html