Python必备技巧之字典(Dictionary)详解

 更新时间:2022年03月24日 14:34:58   作者:Mr数据杨  
Python中的字典由于是对象的集合属于复合数据类型,类似于列表。本文将通过示例详细讲解Python中字典的使用方法,感兴趣的可以了解一下

Python中的字典由于是对象的集合属于复合数据类型,类似于列表。

定义字典

字典是 Python 对数据结构的实现,通常称为关联数组。字典由键值对的集合组成。每个键值对将键映射到其关联的值。

可以通过将逗号分隔的键值对列表括在花括号 ( {} ) 中来定义字典。冒号 ( : ) 将每个键与其关联的值分开。

d = {
    <key>: <value>,
    <key>: <value>,
      .
      .
      .
    <key>: <value>
}

# 定义一个Team
>>> MLB_team = {
...     'Colorado' : 'Rockies',
...     'Boston'   : 'Red Sox',
...     'Minnesota': 'Twins',
...     'Milwaukee': 'Brewers',
...     'Seattle'  : 'Mariners'
... }

可以使用内置dict()函数构建字典。

d = dict([
    (<key>, <value>),
    (<key>, <value),
      .
      .
      .
    (<key>, <value>)
])

# 定义一个Team
>>> MLB_team = dict([
...     ('Colorado', 'Rockies'),
...     ('Boston', 'Red Sox'),
...     ('Minnesota', 'Twins'),
...     ('Milwaukee', 'Brewers'),
...     ('Seattle', 'Mariners')
... ])
# 另一种定义方式
>>> MLB_team = dict(
...     Colorado='Rockies',
...     Boston='Red Sox',
...     Minnesota='Twins',
...     Milwaukee='Brewers',
...     Seattle='Mariners'
... )

字典内容的显示。

>>> type(MLB_team)
<class 'dict'>

>>> MLB_team
{'Colorado': 'Rockies', 'Boston': 'Red Sox', 'Minnesota': 'Twins',
'Milwaukee': 'Brewers', 'Seattle': 'Mariners'}

字典中的条目按定义的顺序显示,使用索引无法指定访问元素。

>>> MLB_team[1]
Traceback (most recent call last):
  File "<pyshell#13>", line 1, in <module>
    MLB_team[1]
KeyError: 1

字典的访问

通过在方括号[]中指定对应的键,从字典中检索值。

>>> MLB_team['Minnesota']
'Twins'
>>> MLB_team['Colorado']
'Rockies'

检索值不在字典中则抛出异常。

>>> MLB_team['Toronto']
Traceback (most recent call last):
  File "<pyshell#19>", line 1, in <module>
    MLB_team['Toronto']
KeyError: 'Toronto'

现有字典添加数据只需分配新的键和值。

>>> MLB_team['Kansas City'] = 'Royals'
>>> MLB_team
{'Colorado': 'Rockies', 'Boston': 'Red Sox', 'Minnesota': 'Twins',
'Milwaukee': 'Brewers', 'Seattle': 'Mariners', 'Kansas City': 'Royals'}

更新数据,只需为现有键分配一个新值。

>>> MLB_team['Seattle'] = 'Seahawks'
>>> MLB_team
{'Colorado': 'Rockies', 'Boston': 'Red Sox', 'Minnesota': 'Twins',
'Milwaukee': 'Brewers', 'Seattle': 'Seahawks', 'Kansas City': 'Royals'}

删除数据,使用 del 指定要删除的键。

>>> del MLB_team['Seattle']
>>> MLB_team
{'Colorado': 'Rockies', 'Boston': 'Red Sox', 'Minnesota': 'Twins',
'Milwaukee': 'Brewers', 'Kansas City': 'Royals'}

字典键与列表索引

经常遇见的一些错误做法。

>>> MLB_team['Toronto']
Traceback (most recent call last):
  File "<pyshell#8>", line 1, in <module>
    MLB_team['Toronto']
KeyError: 'Toronto'

>>> MLB_team[1]
Traceback (most recent call last):
  File "<pyshell#9>", line 1, in <module>
    MLB_team[1]
KeyError: 1

# 数字作为键值使用
>>> d = {0: 'a', 1: 'b', 2: 'c', 3: 'd'}
>>> d
{0: 'a', 1: 'b', 2: 'c', 3: 'd'}
>>> d[0]
'a'
>>> d[2]
'c'

不能将字典视为列表。

>>> type(d)
<class 'dict'>

>>> d[-1]
Traceback (most recent call last):
  File "<pyshell#30>", line 1, in <module>
    d[-1]
KeyError: -1

>>> d[0:2]
Traceback (most recent call last):
  File "<pyshell#31>", line 1, in <module>
    d[0:2]
TypeError: unhashable type: 'slice'

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

增量构建字典

创建新的空字典,然后通过一次添加一个新的键和值构建。

>>> person = {}
>>> type(person)
<class 'dict'>

>>> person['fname'] = 'Joe'
>>> person['lname'] = 'Fonebone'
>>> person['age'] = 51
>>> person['spouse'] = 'Edna'
>>> person['children'] = ['Ralph', 'Betty', 'Joey']
>>> person['pets'] = {'dog': 'Fido', 'cat': 'Sox'}

# 创建和访问字典
>>> person
{'fname': 'Joe', 'lname': 'Fonebone', 'age': 51, 'spouse': 'Edna',
'children': ['Ralph', 'Betty', 'Joey'], 'pets': {'dog': 'Fido', 'cat': 'Sox'}}
>>> person['fname']
'Joe'
>>> person['age']
51
>>> person['children']
['Ralph', 'Betty', 'Joey']

# 检索字典数据
>>> person['children'][-1]
'Joey'
>>> person['pets']['cat']
'Sox'

构建的字典中数据类型没有明确的限制。

>>> foo = {42: 'aaa', 2.78: 'bbb', True: 'ccc'}
>>> foo
{42: 'aaa', 2.78: 'bbb', True: 'ccc'}
>>> foo[42]
'aaa'
>>> foo[2.78]
'bbb'
>>> foo[True]
'ccc'

字典键的限制

几乎任何类型的值都可以用作 Python 中的字典键。

>>> foo = {42: 'aaa', 2.78: 'bbb', True: 'ccc'}
>>> foo
{42: 'aaa', 2.78: 'bbb', True: 'ccc'}

# 可以使用类型和函数等内置对象
>>> d = {int: 1, float: 2, bool: 3}
>>> d
{<class 'int'>: 1, <class 'float'>: 2, <class 'bool'>: 3}
>>> d[float]
2
>>> d = {bin: 1, hex: 2, oct: 3}
>>> d[oct]
3

同一字典内重复的键无法添加,如果添加则对原键的值进行替换。

>>> MLB_team = {
...     'Colorado' : 'Rockies',
...     'Boston'   : 'Red Sox',
...     'Minnesota': 'Twins',
...     'Milwaukee': 'Brewers',
...     'Seattle'  : 'Mariners'
... }

>>> MLB_team['Minnesota'] = 'Timberwolves'
>>> MLB_team
{'Colorado': 'Rockies', 'Boston': 'Red Sox', 'Minnesota': 'Timberwolves',
'Milwaukee': 'Brewers', 'Seattle': 'Mariners'}

元组也可以是字典键,因为元组是不可变的。

>>> d = {(1, 1): 'a', (1, 2): 'b', (2, 1): 'c', (2, 2): 'd'}
>>> d[(1,1)]
'a'
>>> d[(2,1)]
'c'

字典值的限制

字典的中的值是没有任何限制的。

>>> d = {0: 'a', 1: 'a', 2: 'a', 3: 'a'}
>>> d
{0: 'a', 1: 'a', 2: 'a', 3: 'a'}
>>> d[0] == d[1] == d[2]
True

运算符和内置函数

in and not in运算符返回True or False。

>>> MLB_team = {
...     'Colorado' : 'Rockies',
...     'Boston'   : 'Red Sox',
...     'Minnesota': 'Twins',
...     'Milwaukee': 'Brewers',
...     'Seattle'  : 'Mariners'
... }

>>> 'Milwaukee' in MLB_team
True
>>> 'Toronto' in MLB_team
False
>>> 'Toronto' not in MLB_team
True

也可以与短路评估一起使用。

>>> MLB_team['Toronto']
Traceback (most recent call last):
  File "<pyshell#2>", line 1, in <module>
    MLB_team['Toronto']
KeyError: 'Toronto'

>>> 'Toronto' in MLB_team and MLB_team['Toronto']
False

内置字典方法

与字符串和列表一样字典上也是有调用内置方法。

# d.clear() 清空字典数据
>>> d = {'a': 10, 'b': 20, 'c': 30}
>>> d
{'a': 10, 'b': 20, 'c': 30}
>>> d.clear()
>>> d
{}


# d.get(<key>[, <default>]) 如果字典中存在键,则返回该键的值
>>> d = {'a': 10, 'b': 20, 'c': 30}
>>> print(d.get('b'))
20
>>> print(d.get('z'))
None
# <key>未找到并且<default>指定了可选参数
>>> print(d.get('z', -1))
-1


# d.items() 返回字典中的键值对列表
>>> d = {'a': 10, 'b': 20, 'c': 30}
>>> d
{'a': 10, 'b': 20, 'c': 30}
>>> list(d.items())
[('a', 10), ('b', 20), ('c', 30)]
>>> list(d.items())[1][0]
'b'
>>> list(d.items())[1][1]
20


# d.keys() 返回字典中的键列表
>>> d = {'a': 10, 'b': 20, 'c': 30}
>>> d
{'a': 10, 'b': 20, 'c': 30}
>>> list(d.keys())
['a', 'b', 'c']


# d.values() 返回字典中的值列表
>>> d = {'a': 10, 'b': 20, 'c': 30}
>>> d
{'a': 10, 'b': 20, 'c': 30}
>>> list(d.values())
[10, 20, 30]


# d.pop(<key>[, <default>]) 从字典中删除一个键,如果存在并返回它的值
>>> d = {'a': 10, 'b': 20, 'c': 30}
>>> d.pop('b')
20
>>> d
{'a': 10, 'c': 30}
# 如果不存在则引发异常
>>> d = {'a': 10, 'b': 20, 'c': 30}
>>> d.pop('z')
Traceback (most recent call last):
  File "<pyshell#4>", line 1, in <module>
    d.pop('z')
KeyError: 'z'
# 如果指定默认参数<default>则返回该值
>>> d = {'a': 10, 'b': 20, 'c': 30}
>>> d.pop('z', -1)
-1
>>> d
{'a': 10, 'b': 20, 'c': 30}


# d.popitem() 从字典中删除键值对
>>> d = {'a': 10, 'b': 20, 'c': 30}
>>> d.popitem()
('c', 30)
>>> d
{'a': 10, 'b': 20}
>>> d.popitem()
('b', 20)
>>> d
{'a': 10}
# d为空会引发异常
>>> d = {}
>>> d.popitem()
Traceback (most recent call last):
  File "<pyshell#11>", line 1, in <module>
    d.popitem()
KeyError: 'popitem(): dictionary is empty'


# d.update(<obj>) 将字典与另一个字典或可迭代的键值对合并
# (被替换键值).update(替换键值)
>>> d1 = {'a': 10, 'b': 20, 'c': 30}
>>> d2 = {'b': 200, 'd': 400}
>>> d1.update(d2)
>>> d1
{'a': 10, 'b': 200, 'c': 30, 'd': 400}
# 使用元组更新
>>> d1 = {'a': 10, 'b': 20, 'c': 30}
>>> d1.update([('b', 200), ('d', 400)])
>>> d1
{'a': 10, 'b': 200, 'c': 30, 'd': 400}
# 指定关键字参数
>>> d1 = {'a': 10, 'b': 20, 'c': 30}
>>> d1.update(b=200, d=400)
>>> d1
{'a': 10, 'b': 200, 'c': 30, 'd': 400}

到此这篇关于Python必备技巧之字典(Dictionary)详解的文章就介绍到这了,更多相关Python 字典内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • 使用python创建股票的时间序列可视化分析

    使用python创建股票的时间序列可视化分析

    这篇文章主要为大家详细介绍了python创建股票的时间序列可视化分析,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下,希望能够给你带来帮助
    2022-03-03
  • pytorch中tensor.expand()和tensor.expand_as()函数详解

    pytorch中tensor.expand()和tensor.expand_as()函数详解

    今天小编就为大家分享一篇pytorch中tensor.expand()和tensor.expand_as()函数详解,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2019-12-12
  • Python利用PyAutoGUI模块实现控制鼠标键盘

    Python利用PyAutoGUI模块实现控制鼠标键盘

    PyAutoGUI是一个简单易用,跨平台的可以模拟键盘鼠标进行自动操作的python库。本文将详细讲讲它是如何实现控制鼠标键盘的,感兴趣的可以了解一下
    2022-06-06
  • 详解python算法之冒泡排序

    详解python算法之冒泡排序

    这篇文章主要介绍了详解python算法之冒泡排序,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2019-03-03
  • Python实现求最大公约数及判断素数的方法

    Python实现求最大公约数及判断素数的方法

    这篇文章主要介绍了Python实现求最大公约数及判断素数的方法,涉及Python算数运算的相关技巧,需要的朋友可以参考下
    2015-05-05
  • Python基于keras训练实现微笑识别的示例详解

    Python基于keras训练实现微笑识别的示例详解

    Keras是一个由Python编写的开源人工神经网络库,可用于深度学习模型的设计、调试、评估、应用和可视化。本文将基于keras训练实现微笑识别效果,需要的可以参考一下
    2022-01-01
  • python set集合使用方法解析

    python set集合使用方法解析

    这篇文章主要介绍了python set集合使用方法解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2019-11-11
  • Python TKinter如何自动关闭主窗口

    Python TKinter如何自动关闭主窗口

    这篇文章主要介绍了Python TKinter如何自动关闭主窗口,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2020-02-02
  • pytorch 在网络中添加可训练参数,修改预训练权重文件的方法

    pytorch 在网络中添加可训练参数,修改预训练权重文件的方法

    今天小编就为大家分享一篇pytorch 在网络中添加可训练参数,修改预训练权重文件的方法,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2019-08-08
  • Python使用POP3和SMTP协议收发邮件的示例代码

    Python使用POP3和SMTP协议收发邮件的示例代码

    这篇文章主要介绍了Python使用POP3和SMTP协议收发邮件的示例代码,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2019-04-04

最新评论