Home  >  Article  >  Backend Development  >  How to use zip in python dictionary

How to use zip in python dictionary

(*-*)浩
(*-*)浩Original
2019-07-01 11:51:244077browse

This article mainly introduces the usage of Python zip() function, and analyzes the function, usage and related operation precautions of Python zip() function in detail in the form of examples.

How to use zip in python dictionary

Here is an introduction to the use of zip() function in python: (recommended learning: Python video tutorial)

>>> help(zip)
Help on built-in function zip in module __builtin__:
zip(...)
  zip(seq1 [, seq2 [...]]) -> [(seq1[0], seq2[0] ...), (...)]

zip([seq1, ...]) accepts a series of iterable objects as parameters, packs the corresponding elements in the objects into tuples, and then returns a list composed of these tuples . If the lengths of the parameters passed in are not equal, the length of the returned list will be the same as the object with the shortest length among the parameters.

In order to perform calculation operations on dictionary values, you usually need to use the zip() function to first reverse the keys and values.

Example:

prices = {'ACME': 45.23,'AAPL': 612.78,'IBM': 205.55,'HPQ': 37.20,'FB': 10.75}
min_price = min(zip(prices.values(), prices.keys()))
      # min_price is (10.75, 'FB')
      max_price = max(zip(prices.values(), prices.keys()))
      # max_price is (612.78, 'AAPL')

Dictionary values ​​are the same, keys are different, compare the size of the values

>>> prices = { 'AAA' : 45.23, 'ZZZ': 45.23 }
>>> min(zip(prices.values(), prices.keys()))
(45.23, 'AAA')
>>> max(zip(prices.values(), prices.keys()))
(45.23, 'ZZZ')

For more Python related technical articles, please visit Python Learn in the tutorial column!

The above is the detailed content of How to use zip in python dictionary. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn