下面介绍字典采用的主流方法。
1、items()方法
字典的items()方法用于返回该字典所有键-值对的字典视图:
- >>> someone = {'name': 'Wang', 'age': 19, 'hobbies': ['sing songs', 'dance', 'basketball']}
- >>> someone.items()
- dict_items([('name', 'Wang'), ('age', 19), ('hobbies', ['sing songs', 'dance', 'basketball'])])
字典所有键-值对的字典视图同样可以迭代:
- >>> someone = {'name': 'Wang', 'age': 19, 'hobbies': ['sing songs', 'dance', 'basketball']}
- >>> for item in someone.items():
- ... print(item)
- ...
- ('name', 'Wang')
- ('age', 19)
- ('hobbies', ['sing songs', 'dance', 'basketball'])
也可以使用类似嵌套元组解包的形式进行迭代:
- >>> for k, v in someone.items():
- ... print('{0} -> {1}'.format(k, v)) # 使用format()格式化
- ...
- name -> Wang
- age -> 19
- hobbies -> ['sing songs', 'dance', 'basketball']
可以利用items()方法在迭代字典时修改该字典:
- >>> grades = {'math': 69, 'Chinese': 78, 'English': 83}
- >>> for k, v in grades.items():
- ... grades[k] = v - 10 # 将该学生每科成绩都减了10分
- ...
- >>> grades
- {'math': 59, 'Chinese': 68, 'English': 73}
2、update()方法
字典的update()方法使用另一个字典对象或可迭代的键-值对更新字典。如果键不在字典中,那么update()方法将项添加到字典中:
- >>> grades = {'math': 69, 'Chinese': 78, 'English': 83}
- >>> other = {'history': 96, 'physics': 56} # 将使用该字典更新grades字典
- >>> grades.update(other)
- >>> grades # grades字典中新增了两个键-值对
- {'math': 69, 'Chinese': 78, 'English': 83, 'history': 96, 'physics': 56}
- >>> other # other字典并没有改变
- {'history': 96, 'physics': 56}
如果键在字典中,那么update()方法将使用新值更新键:
- >>> grades = {'math': 69, 'Chinese': 78, 'English': 83}
- >>> other = {'history': 96, 'English': 56}
- >>> grades.update(other)
- >>> grades # 键'English'的值更新了
- {'math': 69, 'Chinese': 78, 'English': 56, 'history': 96}
3、pop()方法
前文提到过,字典的pop()方法可以移除指定键并返回该键对应的值,但如果指定的键不在字典中,Python解释器会报错:
- >>> someone = {'name': 'Wang', 'age': 19, 'hobbies': ['sing songs', 'dance', 'basketball']}
- >>> someone.pop('gender') # 键'gender'并不存在
- Traceback (most recent call last):
- File "<stdin>", line 1, in <module>
- KeyError: 'gender'
pop()方法可以提供一个当指定键不存在时的默认值:
- >>> someone = {'name': 'Wang', 'age': 19, 'hobbies': ['sing songs', 'dance', 'basketball']}
- >>> gender = someone.pop('gender', 'famale')
- >>> gender
- 'famale'
- >>> someone # 此时someone字典并没有改变
- {'name': 'Wang', 'age': 19, 'hobbies': ['sing songs', 'dance', 'basketball']}
4、popitem()方法
字典的popitem()方法和列表的pop()方法很像,都是“弹出”并返回一个元素。在Python 3.5及之前的版本中,字典是无序的,因此,popitem()是随机弹出一个项;但从Python 3.6开始,字典是按插入的顺序排列的,因此,popitem()弹出的是最后一个项。
首先验证一下Python 3.5和3.6这两个版本的有序性(Python 2和这两个版本的表现也均不一致,本书不详细探讨)。在Python 3.5中:
- >>> someone = {'name': 'Wang', 'age': 19, 'hobbies': ['sing songs', 'dance', 'basketball']}
- >>> someone # 查看someone
- {'name': 'Wang', 'age': 19, 'hobbies': ['sing songs', 'dance', 'basketball']}
- >>> someone # 再次查看someone,发现它并没有改变
- {'name': 'Wang', 'age': 19, 'hobbies': ['sing songs', 'dance', 'basketball']}
然后关闭Python交互模式,再重新进入Python交互模式:
- >>> someone = {'name': 'Wang', 'age': 19, 'hobbies': ['sing songs', 'dance', 'basketball']}
- >>> someone # someone字典键-值对的顺序发生了改变
- {'hobbies': ['sing songs', 'dance', 'basketball'], 'name': 'Wang', 'age': 19}
- >>> someone
- {'hobbies': ['sing songs', 'dance', 'basketball'], 'name': 'Wang', 'age': 19}
由于在Python 3.5及之前的版本中,字典是无序的,因此,上面的情况可能会出现(由于是随机的,当然也可能顺序不变)。但是从Python 3.6开始,执行和前面一样的操作,无论做多少次,都会得到下面的结果:
- >>> someone = {'name': 'Wang', 'age': 19, 'hobbies': ['sing songs', 'dance', 'basketball']}
- >>> someone
- {'name': 'Wang', 'age': 19, 'hobbies': ['sing songs', 'dance', 'basketball']}
- >>> someone
- {'name': 'Wang', 'age': 19, 'hobbies': ['sing songs', 'dance', 'basketball']}
确认Python 3.6中字典是有序的之后,尝试使用popitems()方法:
- >>> someone = {'name': 'Wang', 'age': 19, 'hobbies': ['sing songs', 'dance', 'basketball']}
- >>> someone.popitem() # 弹出并返回最后一个项
- ('hobbies', ['sing songs', 'dance', 'basketball'])
- >>> someone.popitem()
- ('age', 19)
- >>> someone.popitem()
- ('name', 'Wang')
- >>> someone.popitem() # 如果字典为空,Python解释器会报错
- Traceback (most recent call last):
- File "<stdin>", line 1, in <module>
- KeyError: 'popitem(): dictionary is empty'
5、copy()方法
与列表的copy()方法类似,字典的copy()方法返回一个和被拷贝字典相同的字典(同样是浅复制):
- >>> someone = {'name': 'Wang', 'age': 19, 'hobbies': ['sing songs', 'dance', 'basketball']}
- >>> other = someone.copy()
- >>> other
- {'name': 'Wang', 'age': 19, 'hobbies': ['sing songs', 'dance', 'basketball']}
- >>> other['gender'] = 'female' # other字典中添加一个键-值对
- >>> other # other字典改变了
- {'name': 'Wang', 'age': 19, 'hobbies': ['sing songs', 'dance', 'basketball'], 'gender': 'female'}
- >>> someone # someone字典并没有改变
- {'name': 'Wang', 'age': 19, 'hobbies': ['sing songs', 'dance', 'basketball']}
6、fromkeys()方法
字典的fromkeys()方法用于根据指定序列创建一个新字典,该字典具有用户提供的值。fromkeys()方法返回一个新字典,其中指定序列中的项作为字典的键。如果设置了value参数,那么字典所有键对应的值都将设置为提供的值;如果未设置,那么默认值为None:
- >>> someone = {}.fromkeys(['name', 'age', 'hobbies']) # 默认值为None
- >>> someone
- {'name': None, 'age': None, 'hobbies': None}
- >>> someone = {}.fromkeys(['name', 'age', 'hobbies'], 'a') # 指定默认值
- >>> someone
- {'name': 'a', 'age': 'a', 'hobbies': 'a'}
7、clear()方法
字典的clear()方法用于清除字典中的所有项:
- >>> someone = {'name': 'Wang', 'age': 19, 'hobbies': ['sing songs', 'dance', 'basketball']}
- >>> someone.clear()
- >>> someone # 此时someone字典是一个空字典
- {}