使用Python字典的4个技巧

欢迎关注 “小白玩转Python”,发现更多 “有趣”

引言

尽管每种数据类型都有其优缺点,但字典是我在常用数据容器(例如列表和集合)中最喜欢的。事不宜迟,我想在本文中分享一些超越最基本的字典用例的技巧。我希望它们能对你有所帮助。

1. 创建带有指定键的字典

编写 Python 脚本时,可能需要定义一些全局变量。但是,当稍后在函数中更新这些变量时,必须明确说明这些变量是全局变量。下面是一个简单的例子:

param0 = None
param1 = None




def fetch_params():
    global param0, param1
    param0 = "some value"
    param1 = "some other value"

我不太喜欢这种使用全局关键字的编码模式。当你在多个函数中使用多个全局关键字时,这会很麻烦。相反,可以使用 dictionary 对象来捕获所有相关的变量。在这种情况下,可以直接更新字典,因为它将由解释器全局定位。以下是修改后的代码:

params = dict.fromkeys(["param0", "param1"])




def fetch_params_dict():
    params["param0"] = "some value"
    params["param1"] = "some other value"

如上所示,我使用 fromakeys 类方法实例化 dict 对象。使用这个实例化方法有几个优点:

· 代码更具可读性,因为读者可以清楚地看到您使用这个脚本的参数是什么。

· 当使用方括号获得字典中这些键的值时,将不会收到KeyError异常,因为我    们指定的所有键的初始值都为None,如下所示:

>>> params = dict.fromkeys(["param0", "param1"])
>>> print(params)
{'param0': None, 'param1': None}

2. 列表和字典之间的转换

除了字典之外,列表是我们在项目中经常使用的另一种数据容器类型。列表和字典之间的转换构成双向通信。让我们首先看看如何将列表转换为字典。

如果列表由每个包含两个项的项组成,则可以直接实例化 dictionary 对象。每个项都将成为创建的 dictionary 对象中对应的键值对,如下所示:

>>> # A list of tuples
>>> items0 = [("a", 1), ("b", 2), ("c", 3)]
>>> dict0 = dict(items0)
>>> # A list of lists and tuples
>>> items1 = [["a", 1], ["b", 2], ("c", 3)]
>>> dict1 = dict(items1)
>>> # A zip object
>>> items2 = zip(["a", "b", "c"], [1, 2, 3])
>>> dict2 = dict(items2)
>>> # A tuple object
>>> items3 = (["a", 1], ["b", 2], ("c", 3))
>>> dict3 = dict(items3)
>>> # Evaluation
>>> dict0 == dict1 == dict2 == dict3
True

该代码展示了从列表对象创建字典的几个示例。注意,列表中的项可以是列表或元组,只要每个项只有两个项。

更广泛地说,可以从可迭代对象(列表是一种可迭代对象)中创建字典,并要求可迭代对象的每个项目都具有两个对象。

下面几个例子可以说明如何从现有的字典创建列表。

>>> # Create a dictionary
>>> existing_dict = {"a": 1, "b": 2, "c": 3}
>>> # Create a list contains the keys only
>>> list0 = list(existing_dict)
>>> list1 = list(existing_dict.keys())
>>> print(list0, list1)
['a', 'b', 'c'] ['a', 'b', 'c']
>>> # Create a list contains the values only
>>> list2 = list(existing_dict.values())
>>> print(list2)
[1, 2, 3]
>>> # Create a list contains the key-value pairs
>>> list3 = list(existing_dict.items())
>>> print(list3)
[('a', 1), ('b', 2), ('c', 3)]

第一个用例是创建一个包含现有字典键的对象列表,我们可以简单地将字典传递给列表构造函数。

我们还可以使用values()和items()方法创建值列表或键值对。

除了使用列表构造函数之外,我们还可以使用内置的 sorted ()方法,该方法创建一个有序的列表对象。使用 dictionary 对象,我们可以创建排序的键、值或键值对:

>>> sorted(existing_dict)
['a', 'b', 'c']
>>> sorted(existing_dict.values())
[1, 2, 3]
>>> sorted(existing_dict.items())
[('a', 1), ('b', 2), ('c', 3)]

3.字典迭代

我们可以在 for 循环中直接使用字典,因为它们是一种可迭代对象。默认情况下,可以使用键来迭代,通过在字典对象上调用keys()方法。类似,还可以通过访问值和项的字典视图对象来迭代值和项。以下是一些相关的例子:

>>> # Create a dictionary for iteration
>>> iter_dict = {"a": 1, "b": 2}
>>> for key in iter_dict:
...     print(key)
... 
a
b
>>> for value in iter_dict.values():
...     print(value)
... 
1
2
>>> for key, value in iter_dict.items():
...     print(key, value)
... 
a 1
b 2

除了这些基本迭代之外,您还可以利用一些内置函数,包括sorted()和reversed()。

sorted()方法将按排序顺序创建对象列表。根据指定的内容,可以对键,值或键-值对进行排序。

>>> messed_dict = {"c": 3, "b": 2, "a": 5}
>>> for key, value in sorted(messed_dict.items()):
...     print(key, value)
... 
a 5
b 2
c 3
>>> for value in sorted(messed_dict.values()):
...     print(value)
... 
2
3
5

reversed()方法将创建一个反转对象,该对象反转字典对象的顺序。

>>> ordered_dict = {"a": 1, "b": 2, "c": 3}
>>> ordered_dict = {"a": 1, "b": 2, "c": 3}
... for value in reversed(ordered_dict.values()):
...     print(value)
... 
3
2
1
>>> for key in reversed(ordered_dict):
...     print(key)
... 
c
b
a

4. pop()和popitem()方法

一般情况下,我们不需要从字典对象中删除项,但是在某些情况下,我们可以动态的删除一些项。对比列表,字典中也有pop()方法。

>>> # Create a dictionary object that tracks tips received for the day
>>> tips = {'John': 35.5, 'Aaron': 40.75, 'Ashley': 39}
>>> # Waiters are getting their own tips
... def get_tip(waiter):
...     tip_for_waiter = tips.pop(waiter)
...     print(f"After dispensing ${tip_for_waiter} to {waiter}, \nthe remaining tips are ${tips}.")
...     return tip_for_waiter
... 
>>> get_tip("John")
After dispensing $35.5 to John, 
the remaining tips are ${'Aaron': 40.75, 'Ashley': 39}.
35.5
>>> get_tip("Ashley")
After dispensing $39 to Ashley, 
the remaining tips are ${'Aaron': 40.75}.
39

上面的示例展示了如何使用字典来记录餐馆的小费。

一天结束的时候,服务员排队领取他们自己的那份。我们不希望服务员意外地得到超过他们应得的份额。在此场景中,我们希望在检索到某人的提示时销毁该词典的条目。

如你所见,pop()方法返回键的值,同时从字典中删除整个键值对。

但是需要注意的是,pop()方法可以选择接受一个默认参数,当键不在字典对象中时,该参数将成为返回值,如下所示,当我们没有指定默认值并且字典中没有指定的键时,会引发KeyError。

>>> tips.pop("Daniel")
Traceback (most recent call last):
  File "<input>", line 1, in <module>
KeyError: 'Daniel'
>>> tips.pop("Daniel", 0)
0

除了pop()方法之外,我们还可以使用 popitem()方法破坏性地迭代字典。假设我们有上面讨论过的相同用例。经理不会让服务员得到小费,而是叫他们的名字来分发小费。相关代码如下:

>>> # Create a dictionary object that tracks tips received for the day
>>> tips = {'John': 35.5, 'Aaron': 40.75, 'Ashley': 39}
>>> # Destructively iterate the dictionary
>>> while len(tips):
...     waiter, tip = tips.popitem()
...     print(f"After dispensing ${tip} to {waiter}, \nthe remaining tips are ${tips}.")
... 
After dispensing $39 to Ashley, 
the remaining tips are ${'John': 35.5, 'Aaron': 40.75}.
After dispensing $40.75 to Aaron, 
the remaining tips are ${'John': 35.5}.
After dispensing $35.5 to John, 
the remaining tips are ${}.

popitem()会返回键值对,而不是键值。每次函数调用后,该对将被删除。

请注意,当字典为空时,此方法将引发KeyError。因此在调用此方法之前,使用while循环确保字典不为空很重要。

结论

在本文中,我们回顾了在 Python 中使用 dictionary 的一些有用技巧。这些技巧并不是很复杂,然而掌握它们将使 Python 字典成为项目中更强大的工具。

·  END  ·

HAPPY LIFE

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值