"Python Cookbook" "Data Structure and algorithm" 16. Extracting subsets from a dictionary

Source: Internet
Author: User
Tags pprint

Problem: Want to create a dictionary, which is itself a subset of another dictionary

Solution: Use dictionary derivation (dictionary comprehension) to easily solve

#example of extracting a subset from a dictionary fromPprintImportpprintprices= {   'ACME': 45.23,   'AAPL': 612.78,   'IBM': 205.55,   'HPQ': 37.20,   'FB': 10.75}#Make A dictionary of pricesP1 = {Key:value forKey, ValueinchPrices.items ()ifValue > 200 }Print("All prices") Pprint (p1)#Make A dictionary of tech stocksTech_names = {'AAPL','IBM','HPQ','MSFT'}P2= {Key:value forKey,valueinchPrices.items ()ifKeyinchTech_names}Print("All Techs") Pprint (p2)
>>> ================================ RESTART ================================>>>200 {'AAPL'IBM': 205.55}all techs{'  AAPL'HPQ'IBM': 205.55}

The dictionary-derived scheme is clear and fast to run.

"Python Cookbook" "Data Structure and algorithm" 16. Extracting subsets from a dictionary

Related Article

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.