Home  >  Article  >  Backend Development  >  How to implement calculations on data in dictionaries in Python

How to implement calculations on data in dictionaries in Python

不言
不言forward
2018-10-11 14:29:203855browse

What this article brings to you is about how Python implements calculations on data in a dictionary, such as: maximum value, minimum value, sorting, etc. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you. helped.

1. Requirements

We want to perform various calculations on the data on the dictionary, such as: maximum value, minimum value, sorting, etc.

2. Solution

zip()The function is used to take an iterable object as a parameter, pack the corresponding elements in the object into tuples, and then return a list.

Suppose there is a dictionary that maps stock names and corresponding prices:

prices={
'ACME':45.23,
'AAPL':612.78,
'IBM':205.55,
'HPQ':37.20,
'FB':10.75
}

In order to do useful calculations on the contents of the dictionary, the zip() function is usually used to zip the dictionary The keys and values ​​are reversed.

prices={
'ACME':45.23,
'AAPL':612.78,
'IBM':205.55,
'HPQ':37.20,
'FB':10.75
}
#找出价格最低放入股票
min_price=min(zip(prices.values(),prices.keys()))
print(min_price)
#找出价格最高放入股票
max_price=max(zip(prices.values(),prices.keys()))
print(max_price)

#同样,要对数据排序只要使用zip()再配合sorted()
prices_sorted=sorted(zip(prices.values(),prices.keys()))
print(prices_sorted)

Running result:

(10.75, 'FB')
(612.78, 'AAPL')
[(10.75, 'FB'), (37.2, 'HPQ'), (45.23, 'ACME'), (205.55, 'IBM'), (612.78, 'AAPL')]

Note that the iterator created by zip() can only be consumed once, for example, below

zip_price=zip(prices.values(),prices.keys())
min_price=min(zip_price) #ok
min_price=min(zip_price) #报错


The above is the detailed content of How to implement calculations on data in dictionaries in Python. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:segmentfault.com. If there is any infringement, please contact admin@php.cn delete