python——字典

  (1)除了常用的创建字典的方法以外,python还提供了字典的内置函数dict(),使用该函数创建字典的方法如下:

>>> dict1 = dict((('color','green'),('ponits',5)))  
>>> dict1
{'color': 'green', 'ponits': 5}
>>> dict1 =dict(color = 'green',points = '5')
>>> dict1
{'color': 'green', 'points': '5'}

  第一种方法中,经过help(dict)可知道,dict(mapping)只有一个参数,所以这里用括号的方法先把众多参数修改成一个元组,把元组当成一个参数即可。

  第二种方法中,经过help(dict)可知道,如下:

  dict(**kwargs) -> new dictionary initialized with the name=value pairs
  | in the keyword argument list. For example: dict(one=1, two=2)

  key那里不用加引号,即使是字符串,只需要个等号即可。但是值中加不加引号须看值的类型决定。

     (2) 当然,还有很多创建字典的方式,如下所示:

  (3)fromkeys()函数介绍

  由help(dict)可得,其中有个fromkeys描述如下:

  fromkeys(iterable, value=None, /) from builtins.type | Returns a new dict with keys from iterable and values equal to value.

   fromkeys的常用方法如下:

>>> dict1 = { }           #创建空字典
>>> dict1.fromkeys((1,2,3)) 
{1: None, 2: None, 3: None}          #返回的键值是none
>>> dict1.fromkeys((1,2,3),'Number')
{1: 'Number', 2: 'Number', 3: 'Number'}   #所有的键返回值number
>>> dict1.fromkeys((1,2,3),('one','two','three'))         
{1: ('one', 'two', 'three'), 2: ('one', 'two', 'three'), 3: ('one', 'two', 'three')#所有的键都返回同样的值 没那么智能的匹配

  (4)get()函数介绍

  get(...)| D.get(k[,d]) -> D[k] if k in D, else d. d defaults to None.

>>> dict1 = dict1.fromkeys(range(20),'')
>>> dict1
{0: '', 1: '', 2: '', 3: '', 4: '', 5: '', 6: '', 7: '', 8: '', 9: '', 10: '', 11: '', 12: '', 13: '', 14: '', 15: '', 16: '', 17: '', 18: '', 19: ''}
>>> dict1.get(19)
''
>>> dict1.get(20)
>>> print(dict1.get(20))
None
>>> dict1.get(32,'none')
'none'
>>> dict1
{0: '', 1: '', 2: '', 3: '', 4: '', 5: '', 6: '', 7: '', 8: '', 9: '', 10: '', 11: '', 12: '', 13: '', 14: '', 15: '', 16: '', 17: '', 18: '', 19: ''}
>>> dict1.get(21,'none')
'none'
>>> dict1.get(18,'none')
''

  (5)copy()函数的用法

  copy(...)| D.copy() -> a shallow copy of D       

>>> a = {1:'one',2:'two',3:'three'}
>>> b = a.copy()
>>> c = a
>>> a
{1: 'one', 2: 'two', 3: 'three'}
>>> b
{1: 'one', 2: 'two', 3: 'three'}
>>> c
{1: 'one', 2: 'two', 3: 'three'}
>>> id(a)
63995360
>>> id(b)
64014688
>>> id(c)
63995360             #由以上可知,b与a,c的地址不同。b是单独的地址
>>> c[4] = 'four'
>>> c
{1: 'one', 2: 'two', 3: 'three', 4: 'four'}
>>> a
{1: 'one', 2: 'two', 3: 'three', 4: 'four'}    #修改c后,a也会变,因为他们都是同一个地址
>>> b
{1: 'one', 2: 'two', 3: 'three'}     #b不发生改变,b的地址不一样

  (6) popitem()的用法

1 >>> a
2 {1: 'one', 2: 'two', 3: 'three', 4: 'four'}
3 >>> a.popitem() 
4 (4, 'four')                   #随意弹出任意一个键值对 因为字典是没有顺序的
5 >>> a
6 {1: 'one', 2: 'two', 3: 'three'}         #a更新了

 (7)setdefault()的用法

1 >>> a
2 {1: 'one', 2: 'two', 3: 'three'}
3 >>> a.setdefault('小白')
4 >>> a
5 {1: 'one', 2: 'two', 3: 'three', '小白': None}
6 >>> a.setdefault(5,'five')
7 'five'
8 >>> a
9 {1: 'one', 2: 'two', 3: 'three', '小白': None, 5: 'five'}

 (8)update()的用法

1 >>> b = {'小白':''}
2 >>> a.update(b)
3 >>> a
4 {1: 'one', 2: 'two', 3: 'three', '小白': '', 5: 'five'}
原文地址:https://www.cnblogs.com/carlber/p/9400231.html