[py3]--How to perform some computational operations in the data dictionary (e.g., max, sort, etc.)

Source: Internet
Author: User

Problem

How do I perform some computational operations (such as minimum, maximum, sort, etc.) in a data dictionary?

Solution Zip ()

1. In order to perform a calculation on a dictionary value, it is often necessary to use zip() a function to reverse the key and value.

2. Similarly, you can also use the zip() and sorted() functions to arrange the dictionary data

Prices = {    'ACME': 37.20,    'AAPL': 612.78,    'IBM': 205.55,    'HPQ': 37.20,    'FB': 10.75}Print(min (prices), max (prices))#perform normal math operations directly on a dictionary, which only operates on keys
AAPL IBM

Print # can be resolved through the values function of the dictionary, but only the values are visible when output
10.75 612.78

Print (min (prices,key=Lambda# can be solved by Min/max's key property function, but the output is not as good to see
Fb

Print (min (Zip (prices.values (), Prices.keys ()    ))) # A tuple sequence that "reverses" the Dictionary to (Value,key) by Zip ()
(10.75, ' FB ')

Print (Sorted (Zip (prices.values (), Prices.keys ()   )) # If you happen to have the same values, the results are returned based on the sort result of key.
[('FB' 'ACME' 'HPQ') 'IBM'AAPL')]

3. When performing these calculations, it is important to note that the zip() function creates an iterator that is accessible only once

prices_and_names=Zip (prices.values (), Prices.keys ())print(max (prices_and_names)) ( ' AAPL ' Print(max (prices_and_names))   # The second time you use it, it's an error. is an  empty Sequence

[py3]--How to perform some computational operations in the data dictionary (e.g., max, sort, etc.)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.