The dictionary and collection of Python

Source: Internet
Author: User

Learn about the dictionaries and collections that go into Python.

Review the collection first.

In Python, the collection is represented by set. Curly braces and set () can be used to create collections.

or create an empty collection first

You cannot use s={} to create a collection that creates an empty collection using Set ().

The collection is unordered and non-repeating, so the elements that are duplicated when the collection is created are removed.

Basic operations of the collection:

Hand &

and |

Poor

Symmetrical difference ^

As an example:

Set s1={1,2,3,4}, set s2={2,3,5}

The

>>> s1={1,2,3,4}>>> s2={2,3,5}>>> s1|s2{1, 2, 3, 4, 5}>>> s1&s2{2, 3}>> > S1-s2{1, 4}>>> s1^s2{1, 4, 5}.

Dictionary:

Dictionaries can be called associative stores, dictionaries are indexed by keys, and keys are immutable types, usually with strings and numbers as keys. A dictionary can be thought of as a collection of keys: Values .

The key must be unique in a dictionary. Create an empty dictionary: {}

A common way to create a dictionary:

>>> dic={"A": 1, "B": 2, "C":3}>>> dic{' C ': 3, ' B ': 2, ' a ': 1}>>> dic["a"]1>>> dic["B"] 2>>> dic["C"]3

Returns a list of key values using list (Dic.keys ())

>>> list (Dic.keys ()) [' C ', ' B ', ' a ']

Of course, you can also use Dict () to create a dictionary.

>>> dict ([' Sape ', 4139), (' Guido ', 4127), (' Jack ', 4098)]) {' Sape ': 4139, ' Guido ': 4127, ' Jack ': 4098}

  

The dictionary and collection of Python

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.