Python cookbook (data structure and algorithm) is used to find the similarities between the two dictionaries.

Source: Internet
Author: User

Python cookbook (data structure and algorithm) is used to find the similarities between the two dictionaries.

This example describes how to find the similarities between two dictionaries in Python. We will share this with you for your reference. The details are as follows:

Problem:Find the same places in the two dictionaries (the same key, the same value, etc)

Solution:Passkeys()Oritems()Methods To perform common set operations (such as Union, intersection, and difference set)

>>> A = {'X': 1, 'y': 2, 'z': 3 }>>> B = {'ww ': 10, 'x ': 11, 'y': 2 }>>>. keys () & B. keys () # key intersection {'y', 'x'} >>>. keys ()-B. keys () # key difference set {'Z'} >>>. keys () | B. keys () # key Union {'ww ', 'y', 'x', 'z'}>. items () & B. items () {('y', 2) }>>>. items ()-B. items () {('Z', 3), ('x', 1) }>>. 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 in the dictionary. For example:

>>> C = {key: a [key] for key in. keys ()-{'w', 'z'} # create a new dictionary to remove certain keys> c {'y': 2, 'x ': 1 }>>>

Summary:

Dictionarykeys()Method,items()Methods support set operations,values()Method is not supported. Because the dictionary does not guarantee that all values are unique from the value perspective, which leads to some set operations. However, you can perform this operation by converting the value to a set.

(The code is from Python Cookbook.)

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.