"Python Cookbook" "Data Structure and algorithm" 9. Find the same point in two dictionaries

Source: Internet
Author: User

Problem: Look for two dictionaries in the middle of the same place (same key, same value, etc.)

Solution: Use the keys () or the items () method to perform common collection operations (such as seek a set, intersection, and difference sets)

>>> a={'x': 1,'y': 2,'Z': 3}>>> b={'ww': 10,'x': 11,'y': 2}>>> A.keys () &B.keys () #键的交集 {'y','x'}>>> A.keys ()-B.keys () #键的差集 {'Z'}>>> A.keys () |B.keys () #键的并集 {'ww','y','x','Z'}>>> A.items () &B.items () {('y', 2)}>>> A.items ()-B.items () {('Z', 3), ('x', 1)}>>> A.items () |B.items () {('ww', 10), ('Z', 3), ('x', 1), ('x', 11), ('y', 2)}>>>

These types of operations can also be used to modify or filter out the contents of a dictionary. For example:

 for  in A.keys ()-{'w','z'}}  #  Create a new dictionary with some keys removed >>> c{'y'x' : 1}

Summarize:

The keys () method of the dictionary, the items () method supports collection operations, but the values () method is not supported. Because there is no guarantee that all values are unique in the dictionary from a value perspective, this can cause problems with some collection operations. However, you can do this by turning values into collections.

"Python Cookbook" "Data Structure and algorithm" 9. Find the same point in two dictionaries

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.