>  기사  >  백엔드 개발  >  팁 | 사용하기 쉽고 떼어내기 쉬운 11가지 "파이썬 사전" 지식 포인트!

팁 | 사용하기 쉽고 떼어내기 쉬운 11가지 "파이썬 사전" 지식 포인트!

Python当打之年
Python当打之年앞으로
2023-08-10 14:55:21740검색


파이썬 사전에 관해서는 파이썬에서 매우 중요한 데이터 유형입니다. 기본 지식을 익힌 후 字典이 개념은 후속 학습 및 작업에 동반됩니다.
여기에 모두가 알아야 할 몇 가지 매우 중요한 지식 사항이 있습니다.

사전이 순서가 없나요?

많은 친구들이 이 개념에 대해 명확하지 않을 수 있습니다.
Python 2.7에서 사전은 순서가 지정되지 않은 구조입니다. 사전 항목의 순서가 잘못되었습니다. 이는 항목의 순서가 결정적이고 반복 가능하다는 것을 의미합니다.
>>> # Python 2.7
>>> a_dict = {'color': 'blue', 'fruit': 'apple', 'pet': 'dog'}
>>> a_dict
{'color': 'blue', 'pet': 'dog', 'fruit': 'apple'}
>>> a_dict
{'color': 'blue', 'pet': 'dog', 'fruit': 'apple'}
Python 3.5에서는 사전이 여전히 순서가 없지만 이번에는 임의의 데이터 구조입니다. 즉, 사전을 다시 실행할 때마다 항목의 순서가 달라집니다.
>>> # Python 3.5
>>> a_dict = {'color': 'blue', 'fruit': 'apple', 'pet': 'dog'}
>>> a_dict
{'color': 'blue', 'pet': 'dog', 'fruit': 'apple'}
>>> a_dict
{'color': 'blue', 'pet': 'dog', 'fruit': 'apple'}
Python 3.6 이상에서 사전은 순서가 지정된 데이터 구조입니다. 즉, 요소가 도입된 순서와 동일하게 유지된다는 의미입니다.
>>> a_dict = {'color': 'blue', 'fruit': 'apple', 'pet': 'dog'}
>>> a_dict
{'color': 'blue', 'fruit': 'apple', 'pet': 'dog'}
>>> a_dict
{'color': 'blue', 'fruit': 'apple', 'pet': 'dog'}

키-값 교환

사전이 있는데 어떤 이유로 키를 값으로, 값을 키로 변환해야 한다면 어떻게 해야 할까요?
>>> a_dict = {'one': 1, 'two': 2, 'thee': 3, 'four': 4}
>>> new_dict = {}
>>> for key, value in a_dict.items():
...     new_dict[value] = key
...
>>> new_dict
{1: 'one', 2: 'two', 3: 'thee', 4: 'four'}

특정 조건에 따라 사전 필터링

때로는 특정 조건에 따라 사전을 필터링해야 할 때가 있습니다. 그렇다면 if 조건문과 협력하는 것이 좋은 선택입니다.
>>> a_dict = {'one': 1, 'two': 2, 'thee': 3, 'four': 4}
>>> new_dict = {}  # Create a new empty dictionary
>>> for key, value in a_dict.items():
...     if value <= 2:
...         new_dict[key] = value
...
>>> new_dict
{&#39;one&#39;: 1, &#39;two&#39;: 2}

利用字典中的值,做一些计算

在Python中遍历字典时。需要进行一些计算也是很常见的。假设您已将公司销售额的数据存储在字典中,现在您想知道一年的总收入。
>>> incomes = {&#39;apple&#39;: 5600.00, &#39;orange&#39;: 3500.00, &#39;banana&#39;: 5000.00}
>>> total_income = 0.00
>>> for value in incomes.values():
...     total_income += value  # Accumulate the values in total_income
...
>>> total_income
14100.0

字典推导式

字典推导式,是一个和列表推导式一样,具有很强大功能的知识点。因此,大家一定要掌握。
例如,假设您有两个数据列表,您需要根据它们创建一个新字典。
>>> objects = [&#39;blue&#39;, &#39;apple&#39;, &#39;dog&#39;]
>>> categories = [&#39;color&#39;, &#39;fruit&#39;, &#39;pet&#39;]
>>> a_dict = {key: value for key, value in zip(categories, objects)}
>>> a_dict
{&#39;color&#39;: &#39;blue&#39;, &#39;fruit&#39;: &#39;apple&#39;, &#39;pet&#39;: &#39;dog&#39;}

利用字典推导式,实现键值转换

你会发现,使用字典推导式,是一个更简单、高效的操作。
>>> a_dict = {&#39;one&#39;: 1, &#39;two&#39;: 2, &#39;thee&#39;: 3, &#39;four&#39;: 4}
>>> new_dict = {value: key for key, value in a_dict.items()}
>>> new_dict
{1: &#39;one&#39;, 2: &#39;two&#39;, 3: &#39;thee&#39;, 4: &#39;four&#39;}

利用字典推导式,过滤字典

>>> a_dict = {&#39;one&#39;: 1, &#39;two&#39;: 2, &#39;thee&#39;: 3, &#39;four&#39;: 4}
>>> new_dict = {k: v for k, v in a_dict.items() if v <= 2}
>>> new_dict
{&#39;one&#39;: 1, &#39;two&#39;: 2}

利用字典推导式,做一些计算

>>> incomes = {&#39;apple&#39;: 5600.00, &#39;orange&#39;: 3500.00, &#39;banana&#39;: 5000.00}
>>> total_income = sum([value for value in incomes.values()])
>>> total_income
14100.0

字典排序

从 Python 3.6 开始,字典是有序的数据结构,因此如果您使用 Python 3.6(及更高版本),您将能够通过使用sorted()并借助字典理解对任何字典的键,进行排序。
>> incomes = {&#39;apple&#39;: 5600.00, &#39;orange&#39;: 3500.00, &#39;banana&#39;: 5000.00}
>>> sorted_income = {k: incomes[k] for k in sorted(incomes)}
>>> sorted_income
{&#39;apple&#39;: 5600.0, &#39;banana&#39;: 5000.0, &#39;orange&#39;: 3500.0}

内置函数,与字典配合使用

Python 提供了一些内置函数,这些函数在您处理集合(如字典)时可能会很有用。

map()函数

假设您有一个包含一堆产品价格的字典,并且您需要对它们应用折扣。
>>> prices = {&#39;apple&#39;: 0.40, &#39;orange&#39;: 0.35, &#39;banana&#39;: 0.25}
>>> def discount(current_price):
...     return (current_price[0], round(current_price[1] * 0.95, 2))
...
>>> new_prices = dict(map(discount, prices.items()))
>>> new_prices
{&#39;apple&#39;: 0.38, &#39;orange&#39;: 0.33, &#39;banana&#39;: 0.24}

filter()函数

假设您想知道单价低于0.40的产品。
>>> prices = {&#39;apple&#39;: 0.40, &#39;orange&#39;: 0.35, &#39;banana&#39;: 0.25}
>>> def has_low_price(price):
...     return prices[price] < 0.4
...
>>> low_price = list(filter(has_low_price, prices.keys()))
>>> low_price
[&#39;orange&#39;, &#39;banana&#39;]

字典解包运算符

这是很多人不清楚的概念,Python 3.5 带来了一个有趣的新特性,因此大家需要着重学习。
您可以使用字典解包运算符 ( **) 将两个字典合并为一个新字典。
>>> vegetable_prices = {&#39;pepper&#39;: 0.20, &#39;onion&#39;: 0.55}
>>> fruit_prices = {&#39;apple&#39;: 0.40, &#39;orange&#39;: 0.35, &#39;pepper&#39;: .25}
>>> {**vegetable_prices, **fruit_prices}
{&#39;pepper&#39;: 0.25, &#39;onion&#39;: 0.55, &#39;apple&#39;: 0.4, &#39;orange&#39;: 0.35}
如果您尝试合并的字典,具有重复或公共键,则最右侧字典的值将补充上。

위 내용은 팁 | 사용하기 쉽고 떼어내기 쉬운 11가지 "파이썬 사전" 지식 포인트!의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
이 기사는 Python当打之年에서 복제됩니다. 침해가 있는 경우 admin@php.cn으로 문의하시기 바랍니다. 삭제