How to implement calculations on data in dictionaries in Python

不言
Release: 2018-10-11 14:29:19
forward
3854 people have browsed it

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
}
Copy after login

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)
Copy after login

Running result:

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

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) #报错
Copy after login


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!

Related labels:
source:segmentfault.com
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!