Python: Extracting a subset from a dictionary--dictionary derivation

Source: Internet
Author: User

problem: construct a dictionary, which is a subset of another dictionary

Answer: The simplest way is to use a dictionary derivation

EG1:

1.

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

>>>P1 = {Key:value for key, value in Prices.items () if value > 200}

>>>p1

{' AAPL ': 612.78,' IBM ': 205.55}

2.

dictionary derivation can be done by creating a tuple sequence and then passing it to the dict () Letter number can also be achieved. For example:
>>>P1 = Dict ((key, value) for key, value in Prices.items () if value > 200)

However, the dictionary derivation is clearer and actually runs faster (in this case, the actual test is almost a whole lot faster than the dcit () function).

EG2:

1.

>>>tech_names = {' AAPL ', ' IBM ', ' HPQ ', ' MSFT '}

>>>P2 = {Key:value for key, value in Prices.items () if key in Tech_names}

  {' AAPL ': 612.78, ' IBM ': 205.55, ' HPQ ': 37.20}

2.

>>>tech_names = {' AAPL ', ' IBM ', ' HPQ ', ' MSFT '}

>>>P2 = {Key:prices[key] for key in Prices.keys () & Tech_names}

However, the run-time test results show that this scenario is about 1.6 times times slower than the first scenario. If the performance requirements of the program are relatively high, it will take some time to do the timing test.

Python: Extracting a subset from a dictionary--dictionary derivation

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.