python笔记四-字典

时间:2022-05-12 01:47:07

1、当索引不好用时候,使用字典。

2、字典的定义:

>>> phonebook = {'Alice':'2341','Beth':'9102','Ceil':'3258'}
>>> PHONEBOOK
Traceback (most recent call last):
  File "<pyshell#1>", line 1, in <module>
    PHONEBOOK
NameError: name 'PHONEBOOK' is not defined
>>> phonebook
{'Beth': '9102', 'Alice': '2341', 'Ceil': '3258'}
>>> 

3、使用dict函数将序列建立字典

>>> items = [('name','Gumby'),('age',42)]
>>> d=dict(items)
>>> d
{'age': 42, 'name': 'Gumby'}

>>> d['name']
'Gumby'

删除字典的 键,使用 del d[key], 检测d中是否有key的键,使用 key in d,来判断成员资格

4、创建一个空的字典,符号是{}, 而不是[],创建之后可以直接添加键值,如下:

>>> x = []
>>> x[42] = 'Foobar'
Traceback (most recent call last):
  File "<pyshell#8>", line 1, in <module>
    x[42] = 'Foobar'
IndexError: list assignment index out of range
>>> x = {}
>>> x[42] = 'Foobar'
>>> x
{42: 'Foobar'}

5、利用字典格式化字符串,格式: “%(key)s” % d

>>> phonebook
{'Beth': '9102', 'Alice': '2341', 'Ceil': '3258'}
>>> "Ceil's phone number is %(Ceil)s." % phonebook
"Ceil's phone number is 3258."

>>> "Beth: %(Beth)s" % phonebook
'Beth: 9102'

6、字典方法

(1)clear。将清除原始字典的所有键值

>>> x = {}
>>> x['1'] = 'aaa'
>>> y = x
>>> y
{'1': 'aaa'}
>>> y.clear()
>>> y
{}
>>> x
{}

如果要求只清除x,而保留y的内容,可以执行x={},

(2)copy。执行浅复制

>>> x={'1':'aaa','2':['xx','yy','zz']}
>>> y = x.copy()
>>> y
{'1': 'aaa', '2': ['xx', 'yy', 'zz']}
>>> y['1'] = '111'
>>> x
{'1': 'aaa', '2': ['xx', 'yy', 'zz']}
>>> y
{'1': '111', '2': ['xx', 'yy', 'zz']}

注意:x的键值'1'没有改变,但是对y执行以下操作,x的内容发生了变化

>>> y
{'1': '111', '2': ['xx', 'yy', 'zz']}
>>> y['2'].remove('xx')
>>> y
{'1': '111', '2': ['yy', 'zz']}
>>> x
{'1': 'aaa', '2': ['yy', 'zz']}

注意:x键值'2'在执行remove之后发生了变化,x被修改了,为了达到复制之后相互独立的效果,深复制可以解决以上问题

>>> from copy import deepcopy
>>> d = {}
>>> d['111'] = ['aaa','bbb']
>>> c = d.copy()
>>> dc = deepcopy(d)
>>> d['111'].append('ccc')
>>> c
{'111': ['aaa', 'bbb', 'ccc']}
>>> dc
{'111': ['aaa', 'bbb']}

说明:c会随着d而修改,而dc 则不受影响。

(3)fromkeys 函数,构建字典键值

>>> {}.fromkeys(['key1','key2'])
{'key2': None, 'key1': None}

说明:以上通过空字典创建二对键值(键值列表为key1和key2),默认值为‘None’

>>> dict.fromkeys(['k1','k2','k3','k4'])
{'k4': None, 'k1': None, 'k3': None, 'k2': None}

说明:调用了dict的fromkeys函数

>>> dict.fromkeys(['key1','key2','key3','key4'],'unknown')
{'key1': 'unknown', 'key2': 'unknown', 'key4': 'unknown', 'key3': 'unknown'}

说明:默认值改为了‘unknown’

(4)get方法。可以安全访问字典中不存在的键值,一般常规下根据索引去访问键值会发生异常,而用get方法不会

>>> d = {}
>>> d['a']
Traceback (most recent call last):
  File "<pyshell#2>", line 1, in <module>
    d['a']
KeyError: 'a'
>>> d.get('a')
>>> print(d.get('a'))
None
>>> 

也可以提供默认输出值

>>> d.get('a','N/A')
'N/A'

正常访问存在的键值,如下

>>> d['a'] = 'aaaaa'
>>> d.get(['a'])
Traceback (most recent call last):
  File "<pyshell#7>", line 1, in <module>
    d.get(['a'])
TypeError: unhashable type: 'list'
>>> d.get('a')
'aaaaa'

(5)has_key方法。用来检查字典中是否存在某键key,但是python3.x不包括这个函数

>>> d
{'a': 'aaaaa'}

>>> d.has_key('a')
Traceback (most recent call last):
  File "<pyshell#10>", line 1, in <module>
    d.has_key('a')
AttributeError: 'dict' object has no attribute 'has_key'

可以用in来判断

>>> 'a' in d
True

>>> 'b' in d
False

(6)items和iteritmes,python3.x不支持iteritems,

>>> d = {'1':'aaa', '2':'bbb','3':'ccc','4':'ddd'}
>>> d.items
<built-in method items of dict object at 0x02D8AB20>
>>> d.items()
dict_items([('4', 'ddd'), ('3', 'ccc'), ('2', 'bbb'), ('1', 'aaa')])
>>> it = d.iteritems()
Traceback (most recent call last):
  File "<pyshell#16>", line 1, in <module>
    it = d.iteritems()
AttributeError: 'dict' object has no attribute 'iteritems'
>>> it = d.items
>>> list(it)
Traceback (most recent call last):
  File "<pyshell#18>", line 1, in <module>
    list(it)
TypeError: 'builtin_function_or_method' object is not iterable

(7)keys和iterkeys,python3.x不支持iterkeys

>>> d
{'4': 'ddd', '3': 'ccc', '2': 'bbb', '1': 'aaa'}

>>> d.keys
<built-in method keys of dict object at 0x02D8AB20>
>>> d.keys()
dict_keys(['4', '3', '2', '1'])

(8)pop弹出键值(返回值后从字典中删除)

>>> d
{'4': 'ddd', '3': 'ccc', '2': 'bbb', '1': 'aaa'}
>>> d.pop('1')
'aaa'
>>> d
{'4': 'ddd', '3': 'ccc', '2': 'bbb'}

(9)popitem随机弹出键值

>>> d
{'4': 'ddd', '3': 'ccc', '2': 'bbb'}
>>> d.popitem()
('4', 'ddd')
>>> d
{'3': 'ccc', '2': 'bbb'}

(10)setdefault,当键不存在,使用默认值设置键对应的值,如果存在键,忽略setdefault操作,均返回当前键对应的值

>>> d
{'3': 'ccc', '2': 'bbb'}
>>> d.setdefault('5','N/A')
'N/A'
>>> d
{'5': 'N/A', '3': 'ccc', '2': 'bbb'}
>>> d.setdefault('2','N/A')
'bbb'
>>> d
{'5': 'N/A', '3': 'ccc', '2': 'bbb'}

(11)update。用新字典的键值替换旧字典的键值

>>> d
{'5': 'N/A', '3': 'ccc', '2': 'bbb'}

>>> d1 = {'5':'eee'}
>>> d.update(d1)
>>> d
{'5': 'eee', '3': 'ccc', '2': 'bbb'}

(12)values和 itervalues

>>> d
{'5': 'eee', '3': 'ccc', '2': 'bbb'}

>>> d.values
<built-in method values of dict object at 0x02D8AB20>
>>> d.values()
dict_values(['eee', 'ccc', 'bbb'])

python3不支持value迭代器

>>> itv = d.values
>>> list(itv)
Traceback (most recent call last):
  File "<pyshell#41>", line 1, in <module>
    list(itv)
TypeError: 'builtin_function_or_method' object is not iterable
>>> itv = d.itervalues
Traceback (most recent call last):
  File "<pyshell#42>", line 1, in <module>
    itv = d.itervalues
AttributeError: 'dict' object has no attribute 'itervalues'
>>> itv = d.itervalues()
Traceback (most recent call last):
  File "<pyshell#43>", line 1, in <module>
    itv = d.itervalues()
AttributeError: 'dict' object has no attribute 'itervalues'