当前位置:  首页>> 技术小册>> Python合辑6-字典专题

字典是否是无序的

关于这个概念,很多朋友不一定清楚。
在 Python 2.7 中,字典是无序结构。字典项目的顺序是混乱的。这意味着项目的顺序是确定性和可重复的。

  1. >>> # Python 2.7
  2. >>> a_dict = {'color': 'blue', 'fruit': 'apple', 'pet': 'dog'}
  3. >>> a_dict
  4. {'color': 'blue', 'pet': 'dog', 'fruit': 'apple'}
  5. >>> a_dict
  6. {'color': 'blue', 'pet': 'dog', 'fruit': 'apple'}

在 Python 3.5 中,字典仍然是无序的,但这次是随机的数据结构。这意味着每次重新运行字典时,都会得到不同的项目顺序。

  1. >>> # Python 3.5
  2. >>> a_dict = {'color': 'blue', 'fruit': 'apple', 'pet': 'dog'}
  3. >>> a_dict
  4. {'color': 'blue', 'pet': 'dog', 'fruit': 'apple'}
  5. >>> a_dict
  6. {'color': 'blue', 'pet': 'dog', 'fruit': 'apple'}

在 Python 3.6 及更高版本中,字典是有序的数据结构,这意味着它们保持元素的顺序与它们被引入时的顺序相同。

  1. >>> a_dict = {'color': 'blue', 'fruit': 'apple', 'pet': 'dog'}
  2. >>> a_dict
  3. {'color': 'blue', 'fruit': 'apple', 'pet': 'dog'}
  4. >>> a_dict
  5. {'color': 'blue', 'fruit': 'apple', 'pet': 'dog'}

键值互换

假设有一本字典,由于某种原因需要将键转换为值,值转换为键,应该怎么做呢?

  1. >>> a_dict = {'one': 1, 'two': 2, 'three': 3, 'four': 4}
  2. >>> new_dict = {}
  3. >>> for key, value in a_dict.items():
  4. ... new_dict[value] = key
  5. ...
  6. >>> new_dict
  7. {1: 'one', 2: 'two', 3: 'three', 4: 'four'}
  8. # 另一种更快捷的实现方式
  9. >>> new_dict = {v:k for k,v in a_dict.items()}

依据某种条件,过滤字典

有时候,需要根据某种条件来过滤字典。那么配合if条件语句,是一个很好的选择。

  1. >>> a_dict = {'one': 1, 'two': 2, 'thee': 3, 'four': 4}
  2. >>> new_dict = {} # Create a new empty dictionary
  3. >>> for key, value in a_dict.items():
  4. ... if value <= 2:
  5. ... new_dict[key] = value
  6. ...
  7. >>> new_dict
  8. {'one': 1, 'two': 2}

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

在Python中遍历字典时。需要进行一些计算也是很常见的。假设已将公司销售额的数据存储在字典中,现在想知道一年的总收入。

  1. >>> incomes = {'apple': 5600.00, 'orange': 3500.00, 'banana': 5000.00}
  2. >>> total_income = 0.00
  3. >>> for value in incomes.values():
  4. ... total_income += value # Accumulate the values in total_income
  5. ...
  6. >>> total_income
  7. 14100.0

字典推导式

字典推导式,是一个和列表推导式一样,具有很强大功能的知识点。因此,大家一定要掌握。
例如,假设有两个数据列表,需要根据它们创建一个新字典。

  1. >>> objects = ['blue', 'apple', 'dog']
  2. >>> categories = ['color', 'fruit', 'pet']
  3. >>> a_dict = {key: value for key, value in zip(categories, objects)}
  4. >>> a_dict
  5. {'color': 'blue', 'fruit': 'apple', 'pet': 'dog'}

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

可以发现,使用字典推导式,是一个更简单、高效的操作。

  1. >>> a_dict = {'one': 1, 'two': 2, 'thee': 3, 'four': 4}
  2. >>> new_dict = {value: key for key, value in a_dict.items()}
  3. >>> new_dict
  4. {1: 'one', 2: 'two', 3: 'thee', 4: 'four'}

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

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

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

  1. >>> incomes = {'apple': 5600.00, 'orange': 3500.00, 'banana': 5000.00}
  2. >>> total_income = sum([value for value in incomes.values()])
  3. >>> total_income
  4. 14100.0

字典排序

从 Python 3.6 开始,字典是有序的数据结构,因此如果使用 Python 3.6(及更高版本),能够通过使用sorted()并借助字典理解对任何字典的键,进行排序。

  1. >> incomes = {'apple': 5600.00, 'orange': 3500.00, 'banana': 5000.00}
  2. >>> sorted_income = {k: incomes[k] for k in sorted(incomes)}
  3. >>> sorted_income
  4. {'apple': 5600.0, 'banana': 5000.0, 'orange': 3500.0}

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

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

map()函数
假设有一个包含一堆产品价格的字典,并且需要对它们应用折扣。

  1. >>> prices = {'apple': 0.40, 'orange': 0.35, 'banana': 0.25}
  2. >>> def discount(current_price):
  3. ... return (current_price[0], round(current_price[1] * 0.95, 2))
  4. ...
  5. >>> new_prices = dict(map(discount, prices.items()))
  6. >>> new_prices
  7. {'apple': 0.38, 'orange': 0.33, 'banana': 0.24}

filter()函数
假设要知道单价低于0.40的产品。

  1. >>> prices = {'apple': 0.40, 'orange': 0.35, 'banana': 0.25}
  2. >>> def has_low_price(price):
  3. ... return prices[price] < 0.4
  4. ...
  5. >>> low_price = list(filter(has_low_price, prices.keys()))
  6. >>> low_price
  7. ['orange', 'banana']

字典解包运算符

这是很多人不清楚的概念,Python 3.5 带来了一个有趣的新特性,因此大家需要着重学习。
可以使用字典解包运算符 (**) 将两个字典合并为一个新字典。

  1. >>> vegetable_prices = {'pepper': 0.20, 'onion': 0.55}
  2. >>> fruit_prices = {'apple': 0.40, 'orange': 0.35, 'pepper': .25}
  3. >>> {**vegetable_prices, **fruit_prices}
  4. {'pepper': 0.25, 'onion': 0.55, 'apple': 0.4, 'orange': 0.35}

如果尝试合并的字典,具有重复或公共键,则最右侧字典的值将补充上。


该分类下的相关小册推荐: