【Python基础知识】Python字典方法汇总(下)

发布 : python培训      来源:python干货资料

2020-08-12 20:06:11

下面介绍字典采用的主流方法。

1、items()方法

字典的items()方法用于返回该字典所有键-值对的字典视图:

  1. >>> someone = {'name': 'Wang', 'age': 19, 'hobbies': ['sing songs', 'dance', 'basketball']}
  2. >>> someone.items()
  3. dict_items([('name', 'Wang'), ('age', 19), ('hobbies', ['sing songs', 'dance', 'basketball'])])

字典所有键-值对的字典视图同样可以迭代:

  1. >>> someone = {'name': 'Wang', 'age': 19, 'hobbies': ['sing songs', 'dance', 'basketball']}
  2. >>> for item in someone.items():
  3. ... print(item)
  4. ...
  5. ('name', 'Wang')
  6. ('age', 19)
  7. ('hobbies', ['sing songs', 'dance', 'basketball'])

也可以使用类似嵌套元组解包的形式进行迭代:

  1. >>> for k, v in someone.items():
  2. ... print('{0} -> {1}'.format(k, v)) # 使用format()格式化
  3. ...
  4. name -> Wang
  5. age -> 19
  6. hobbies -> ['sing songs', 'dance', 'basketball']

可以利用items()方法在迭代字典时修改该字典:

  1. >>> grades = {'math': 69, 'Chinese': 78, 'English': 83}
  2. >>> for k, v in grades.items():
  3. ... grades[k] = v - 10 # 将该学生每科成绩都减了10分
  4. ...
  5. >>> grades
  6. {'math': 59, 'Chinese': 68, 'English': 73}

2、update()方法

字典的update()方法使用另一个字典对象或可迭代的键-值对更新字典。如果键不在字典中,那么update()方法将项添加到字典中:

  1. >>> grades = {'math': 69, 'Chinese': 78, 'English': 83}
  2. >>> other = {'history': 96, 'physics': 56} # 将使用该字典更新grades字典
  3. >>> grades.update(other)
  4. >>> grades # grades字典中新增了两个键-值对
  5. {'math': 69, 'Chinese': 78, 'English': 83, 'history': 96, 'physics': 56}
  6. >>> other # other字典并没有改变
  7. {'history': 96, 'physics': 56}

如果键在字典中,那么update()方法将使用新值更新键:

  1. >>> grades = {'math': 69, 'Chinese': 78, 'English': 83}
  2. >>> other = {'history': 96, 'English': 56}
  3. >>> grades.update(other)
  4. >>> grades # 键'English'的值更新了
  5. {'math': 69, 'Chinese': 78, 'English': 56, 'history': 96}

3、pop()方法

前文提到过,字典的pop()方法可以移除指定键并返回该键对应的值,但如果指定的键不在字典中,Python解释器会报错:

  1. >>> someone = {'name': 'Wang', 'age': 19, 'hobbies': ['sing songs', 'dance', 'basketball']}
  2. >>> someone.pop('gender') # 键'gender'并不存在
  3. Traceback (most recent call last):
  4. File "<stdin>", line 1, in <module>
  5. KeyError: &#39;gender&#39;

pop()方法可以提供一个当指定键不存在时的默认值:

  1. >>> someone = {&#39;name&#39;: &#39;Wang&#39;, &#39;age&#39;: 19, &#39;hobbies&#39;: [&#39;sing songs&#39;, &#39;dance&#39;, &#39;basketball&#39;]}
  2. >>> gender = someone.pop(&#39;gender&#39;, &#39;famale&#39;)
  3. >>> gender
  4. &#39;famale&#39;
  5. >>> someone # 此时someone字典并没有改变
  6. {&#39;name&#39;: &#39;Wang&#39;, &#39;age&#39;: 19, &#39;hobbies&#39;: [&#39;sing songs&#39;, &#39;dance&#39;, &#39;basketball&#39;]}

4、popitem()方法

字典的popitem()方法和列表的pop()方法很像,都是“弹出”并返回一个元素。在Python 3.5及之前的版本中,字典是无序的,因此,popitem()是随机弹出一个项;但从Python 3.6开始,字典是按插入的顺序排列的,因此,popitem()弹出的是最后一个项。

首先验证一下Python 3.5和3.6这两个版本的有序性(Python 2和这两个版本的表现也均不一致,本书不详细探讨)。在Python 3.5中:

  1. >>> someone = {&#39;name&#39;: &#39;Wang&#39;, &#39;age&#39;: 19, &#39;hobbies&#39;: [&#39;sing songs&#39;, &#39;dance&#39;, &#39;basketball&#39;]}
  2. >>> someone # 查看someone
  3. {&#39;name&#39;: &#39;Wang&#39;, &#39;age&#39;: 19, &#39;hobbies&#39;: [&#39;sing songs&#39;, &#39;dance&#39;, &#39;basketball&#39;]}
  4. >>> someone # 再次查看someone,发现它并没有改变
  5. {&#39;name&#39;: &#39;Wang&#39;, &#39;age&#39;: 19, &#39;hobbies&#39;: [&#39;sing songs&#39;, &#39;dance&#39;, &#39;basketball&#39;]}

然后关闭Python交互模式,再重新进入Python交互模式:

  1. >>> someone = {&#39;name&#39;: &#39;Wang&#39;, &#39;age&#39;: 19, &#39;hobbies&#39;: [&#39;sing songs&#39;, &#39;dance&#39;, &#39;basketball&#39;]}
  2. >>> someone # someone字典键-值对的顺序发生了改变
  3. {&#39;hobbies&#39;: [&#39;sing songs&#39;, &#39;dance&#39;, &#39;basketball&#39;], &#39;name&#39;: &#39;Wang&#39;, &#39;age&#39;: 19}
  4. >>> someone
  5. {&#39;hobbies&#39;: [&#39;sing songs&#39;, &#39;dance&#39;, &#39;basketball&#39;], &#39;name&#39;: &#39;Wang&#39;, &#39;age&#39;: 19}

由于在Python 3.5及之前的版本中,字典是无序的,因此,上面的情况可能会出现(由于是随机的,当然也可能顺序不变)。但是从Python 3.6开始,执行和前面一样的操作,无论做多少次,都会得到下面的结果:

  1. >>> someone = {&#39;name&#39;: &#39;Wang&#39;, &#39;age&#39;: 19, &#39;hobbies&#39;: [&#39;sing songs&#39;, &#39;dance&#39;, &#39;basketball&#39;]}
  2. >>> someone
  3. {&#39;name&#39;: &#39;Wang&#39;, &#39;age&#39;: 19, &#39;hobbies&#39;: [&#39;sing songs&#39;, &#39;dance&#39;, &#39;basketball&#39;]}
  4. >>> someone
  5. {&#39;name&#39;: &#39;Wang&#39;, &#39;age&#39;: 19, &#39;hobbies&#39;: [&#39;sing songs&#39;, &#39;dance&#39;, &#39;basketball&#39;]}

确认Python 3.6中字典是有序的之后,尝试使用popitems()方法:

  1. >>> someone = {&#39;name&#39;: &#39;Wang&#39;, &#39;age&#39;: 19, &#39;hobbies&#39;: [&#39;sing songs&#39;, &#39;dance&#39;, &#39;basketball&#39;]}
  2. >>> someone.popitem() # 弹出并返回最后一个项
  3. (&#39;hobbies&#39;, [&#39;sing songs&#39;, &#39;dance&#39;, &#39;basketball&#39;])
  4. >>> someone.popitem()
  5. (&#39;age&#39;, 19)
  6. >>> someone.popitem()
  7. (&#39;name&#39;, &#39;Wang&#39;)
  8. >>> someone.popitem() # 如果字典为空,Python解释器会报错
  9. Traceback (most recent call last):
  10. File "<stdin>", line 1, in <module>
  11. KeyError: &#39;popitem(): dictionary is empty&#39;

5、copy()方法

与列表的copy()方法类似,字典的copy()方法返回一个和被拷贝字典相同的字典(同样是浅复制):

  1. >>> someone = {&#39;name&#39;: &#39;Wang&#39;, &#39;age&#39;: 19, &#39;hobbies&#39;: [&#39;sing songs&#39;, &#39;dance&#39;, &#39;basketball&#39;]}
  2. >>> other = someone.copy()
  3. >>> other
  4. {&#39;name&#39;: &#39;Wang&#39;, &#39;age&#39;: 19, &#39;hobbies&#39;: [&#39;sing songs&#39;, &#39;dance&#39;, &#39;basketball&#39;]}
  5. >>> other[&#39;gender&#39;] = &#39;female&#39; # other字典中添加一个键-值对
  6. >>> other # other字典改变了
  7. {&#39;name&#39;: &#39;Wang&#39;, &#39;age&#39;: 19, &#39;hobbies&#39;: [&#39;sing songs&#39;, &#39;dance&#39;, &#39;basketball&#39;], &#39;gender&#39;: &#39;female&#39;}
  8. >>> someone # someone字典并没有改变
  9. {&#39;name&#39;: &#39;Wang&#39;, &#39;age&#39;: 19, &#39;hobbies&#39;: [&#39;sing songs&#39;, &#39;dance&#39;, &#39;basketball&#39;]}

6、fromkeys()方法

字典的fromkeys()方法用于根据指定序列创建一个新字典,该字典具有用户提供的值。fromkeys()方法返回一个新字典,其中指定序列中的项作为字典的键。如果设置了value参数,那么字典所有键对应的值都将设置为提供的值;如果未设置,那么默认值为None:

  1. >>> someone = {}.fromkeys([&#39;name&#39;, &#39;age&#39;, &#39;hobbies&#39;]) # 默认值为None
  2. >>> someone
  3. {&#39;name&#39;: None, &#39;age&#39;: None, &#39;hobbies&#39;: None}
  4. >>> someone = {}.fromkeys([&#39;name&#39;, &#39;age&#39;, &#39;hobbies&#39;], &#39;a&#39;) # 指定默认值
  5. >>> someone
  6. {&#39;name&#39;: &#39;a&#39;, &#39;age&#39;: &#39;a&#39;, &#39;hobbies&#39;: &#39;a&#39;}

7、clear()方法

字典的clear()方法用于清除字典中的所有项:

  1. >>> someone = {&#39;name&#39;: &#39;Wang&#39;, &#39;age&#39;: 19, &#39;hobbies&#39;: [&#39;sing songs&#39;, &#39;dance&#39;, &#39;basketball&#39;]}
  2. >>> someone.clear()
  3. >>> someone # 此时someone字典是一个空字典
  4. {}

THE END  

声明:本站稿件版权均属中公教育优就业所有,未经许可不得擅自转载。

领取零基础自学IT资源

涉及方向有Java、Web前端、UI设计、软件测试、python等科目,内容包含学习路线、视频、源码等

点击申请领取资料

点击查看资料详情 

收起 


 相关推荐

问题解答专区
返回顶部