【Python】11、python内置数
一、字典
1、字典的初始化
字典是一种key-value结构,和set一样是无序的
In [160]: d = {}
In [161]: type(d)
Out[161]: dict
In [166]: d = {'a':1, 'b':2}
In [167]: d
Out[167]: {'a': 1, 'b': 2}
In [180]: d = dict({"a":0, "b":1})
In [181]: d
Out[181]: {'a': 0, 'b': 1}
In [164]: d = dict([["a", 1], ["b", 2]]) # 可迭代对象的元素必须是一个二元组
In [165]: d
Out[165]: {'a': 1, 'b': 2}
In [168]: d = dict.fromkeys(range(5)) # 传入的可迭代元素为key,值为None
In [169]: d
Out[169]: {0: None, 1: None, 2: None, 3: None, 4: None}
In [170]: d = dict.fromkeys(range(5), "abc") # 传入的可迭代元素为key,值为abc
In [171]: d
Out[171]: {0: 'abc', 1: 'abc', 2: 'abc', 3: 'abc', 4: 'abc'}
二、字典的基本操作
1、增和改
In [173]: d = {'a':1, 'b':2} # 直接使用key做为索引,对某个不存在的索引赋值会增加KV对
In [174]: d["c"] = 1
In [175]: d
Out[175]: {'a': 1, 'b': 2, 'c': 1}
In [175]: d
Out[175]: {'a': 1, 'b': 2, 'c': 1}
In [176]: d["b"] = 1
In [177]: d
Out[177]: {'a': 1, 'b': 1, 'c': 1}
## dict.update() 通常用于合并dict
In [178]: d.update((("d", 4),("e", 5)))
In [179]: d
Out[179]: {'a': 1, 'b': 1, 'c': 1, 'd': 4, 'e': 5}
In [1]: d = {'a':1, 'b':2}
In [2]: d.update({'c':3, 'd':4})
In [3]: d
Out[3]: {'a': 1, 'b': 2, 'c': 3, 'd': 4}
In [6]: d.update({'c':3, 'd':44}) # 当键存在时,其值会更新
In [7]: d
Out[7]: {'a': 1, 'b': 2, 'c': 3, 'd': 44}
2、删
## dict.pop()
In [23]: help(d.pop)
Help on built-in function pop:
pop(...) method of builtins.dict instance
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
(END)
In [24]: d
Out[24]: {'a': 11, 'b': 2}
In [25]: d.pop('a')
Out[25]: 11
In [26]: d.pop('c')
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
<ipython-input-26-adf338c8a0db> in <module>()
----> 1 d.pop('c')
KeyError: 'c'
In [27]: d.pop('c', 555)
Out[27]: 555
In [28]: d.pop('b', 555)
Out[28]: 2
In [30]: d
Out[30]: {}
## dict.popitem 随机返回一个KV对的二元组
In [33]: help(d.popitem)
Help on built-in function popitem:
popitem(...) method of builtins.dict instance
D.popitem() -> (k, v), remove and return some (key, value) pair as a
2-tuple; but raise KeyError if D is empty.
In [35]: d = {'a':1, 'b':2}
In [36]: d
Out[36]: {'a': 1, 'b': 2}
In [37]: d.popitem()
Out[37]: ('b', 2)
In [38]: d
Out[38]: {'a': 1}
In [39]: d.popitem()
Out[39]: ('a', 1)
In [40]: d
Out[40]: {}
In [41]: d.popitem()
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
<ipython-input-41-5d3e77a54ba7> in <module>()
----> 1 d.popitem()
KeyError: 'popitem(): dictionary is empty'
## dict.clear()
In [52]: d = {'a':1}
In [53]: d.clear()
In [54]: d
Out[54]: {}
In [55]: d.clear()
## del
In [61]: d = {'a':1}
In [62]: del d['a']
In [63]: d
Out[63]: {}
In [64]: del d
In [65]: d
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-65-e29311f6f1bf> in <module>()
----> 1 d
NameError: name 'd' is not defined
能修改dict的key吗?
只能通过先删除一个key再增加一个key来变相修改
2、查
1)单个元素的访问
In [1]: d = {'a':1, 'b':2}
In [2]: d
Out[2]: {'a': 1, 'b': 2}
In [3]: d['a']
Out[3]: 1
In [4]: d['c']
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
<ipython-input-4-3e4d85f12902> in <module>()
----> 1 d['c']
KeyError: 'c'
## dict.get()
In [5]: help(d.get)
Help on built-in function get:
get(...) method of builtins.dict instance
D.get(k[,d]) -> D[k] if k in D, else d. d defaults to None.
(END)
In [6]: d
Out[6]: {'a': 1, 'b': 2}
In [7]: d.get('a')
Out[7]: 1
In [8]: d.get('c')
In [9]: d
Out[9]: {'a': 1, 'b': 2}
In [12]: d.get('c', 123)
Out[12]: 123
In [13]: d
Out[13]: {'a': 1, 'b': 2}
## dict.setdefault() 获取K的值,K不存在时则新增该K和其V,V默认为None
In [14]: help(d.setdefault)
Help on built-in function setdefault:
setdefault(...) method of builtins.dict instance
D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D
(END)
In [15]: d
Out[15]: {'a': 1, 'b': 2}
In [16]: d.setdefault('a')
Out[16]: 1
In [17]: d.setdefault('c')
In [18]: d
Out[18]: {'a': 1, 'b': 2, 'c': None}
In [19]: d.setdefault('d', 123)
Out[19]: 123
In [20]: d
Out[20]: {'a': 1, 'b': 2, 'c': None, 'd': 123}
In [21]: d.setdefault('a', 123)
Out[21]: 1
In [22]: d
Out[22]: {'a': 1, 'b': 2, 'c': None, 'd': 123}
1)元素的遍历
dict的元素是成对出现的
In [23]: d
Out[23]: {'a': 1, 'b': 2, 'c': None, 'd': 123}
In [24]: for i in d:
...: print(i)
...:
a
b
c
d
In [25]:
直接用for in 遍历dict、遍历的是key
dict.keys()
In [25]: help(d.keys)
Help on built-in function keys:
keys(...) method of builtins.dict instance
D.keys() -> a set-like object providing a view on D's keys
(END)
In [26]: d
Out[26]: {'a': 1, 'b': 2, 'c': None, 'd': 123}
In [27]: d.keys()
Out[27]: dict_keys(['a', 'b', 'c', 'd'])
dict.values():
In [29]: d
Out[29]: {'a': 1, 'b': 2, 'c': None, 'd': 123}
In [30]: d.values()
Out[30]: dict_values([1, 2, None, 123])
In [35]: lst = list(d.values())
In [36]: lst
Out[36]: [1, 2, None, 123]
dict.items()
In [37]: d
Out[37]: {'a': 1, 'b': 2, 'c': None, 'd': 123}
In [38]: d.items()
Out[38]: dict_items([('a', 1), ('b', 2), ('c', None), ('d', 123)])
In [39]: lst = d.items()
In [40]: type(lst)
Out[40]: dict_items
In [41]: lst = list(d.items())
In [42]: lst
Out[42]: [('a', 1), ('b', 2), ('c', None), ('d', 123)]
In [43]: for k, v in d.items():
...: print(k, v)
...:
a 1
b 2
c None
d 123
In [44]:
dict.keys()、dict.value()、dict.items()返回的都类似生成器;它并不会复制一份内存
python2中队友的方法返回的list,会复制一份内存
字典对Key和Value的限制:
字典的key需要不重复、可hash
字典是无序的
三、标准库中dict的变体
1、defaultdict 默认字典
In [3]: from collections import defaultdict
In [4]: d1 = {}
In [5]: d2 = defaultdict()
In [6]: type(d1)
Out[6]: dict
In [7]: type(d2)
Out[7]: collections.defaultdict
In [8]: d1
Out[8]: {}
In [9]: d2
Out[9]: defaultdict(None, {})
In [46]: d2['a'] = 11
In [47]: d2
Out[47]: defaultdict(None, {'a': 11})
In [12]: help(defaultdict)
Help on class defaultdict in module collections:
class defaultdict(builtins.dict)
| defaultdict(default_factory[, ...]) --> dict with default factory
|
| The default factory is called without arguments to produce
| a new value when a key is not present, in __getitem__ only.
| A defaultdict compares equal to a dict with the same items.
| All remaining arguments are treated the same as if they were
| passed to the dict constructor, including keyword arguments.
|
| Method resolution order:
| defaultdict
| builtins.dict
| builtins.object
In [13]: d2 = defaultdict(list)
In [14]: d2
Out[14]: defaultdict(list, {})
In [15]: d1['a']
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
<ipython-input-15-a9ea8faf9ae0> in <module>()
----> 1 d1['a']
KeyError: 'a'
In [16]: d2['a']
Out[16]: []
In [19]: d2
Out[19]: defaultdict(list, {'a': []})
In [20]: d2['a']
Out[20]: []
In [21]: d2
Out[21]: defaultdict(list, {'a': []})
In [22]: d2['a'] = 11
In [23]: d2
Out[23]: defaultdict(list, {'a': 11})
In [24]: d2['a']
Out[24]: 11
default初始化的时候,需要传入一个函数,这个函数也交工厂函数,当我们使用下标访问key的时候,如果这个key不存在,defaultdict会自动调用初始化时传入的函数,生成一个对象作为这个key的value。
2、有序字典
In [58]: from collections import OrderedDict
In [59]: d = OrderedDict()
In [60]: d
Out[60]: OrderedDict()
In [61]: d['a'] = 1
In [62]: d['b'] = 2
In [63]: d['c'] = 3
In [64]: d
Out[64]: OrderedDict([('a', 1), ('b', 2), ('c', 3)])
In [65]: for k, v in d.items():
...: print(k, v)
...:
a 1
b 2
c 3
有序dict会保持插入顺序
免责声明:
① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。
② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341