A Dictionary of Python

Source: Internet
Author: User

1. Create a dictionary with {}

Code:

12 ={"a":"1""b":"2"}printx

Output:

{' A ': ' 1 ', ' B ': ' 2 '}

2, with the built-in function dict () 1), the entry parameter is similar to a= "1" the key value pair

Code:

12 =dict(a="1", b="2")printx

Output:

{' A ': ' 1 ', ' B ': ' 2 '}

2), the entry parameter is a tuple, within the tuple is a series of tuples containing two values, for example (("A", "1"), ("B", "2")

Code:

12 =dict((("a""1"), ("b""2")))printx

Output

{' A ': ' 1 ', ' B ': ' 2 '}

3), the entry is a tuple, within the tuple is a series of two values of the list, for example (["A", "1"], ["B", "2"])

Code:

12 =dict((["a""1"], ["b""2"]))printx

Output:

{' A ': ' 1 ', ' B ': ' 2 '}

4), enter the parameter as a list, inside the list is a series of tuples containing two values, for example [("A", "1"), ("B", "2")]

Code:

12 =dict([("a""1"),("b""2")])printx

Output:

{' A ': ' 1 ', ' B ': ' 2 '}

5), enter the parameter as a list, inside the list is a list of two values, for example [["A", "1"],["B", "2"]

Code:

12 =dict([["a""1"],["b""2"]])printx

Output:

{' A ': ' 1 ', ' B ': ' 2 '}

Attention:

    • For a= "1" to initialize the dictionary, the dictionary key can only be a string, and the string is not quoted

    • For dict built-in function initialization when the entry parameter is a tuple, for example 1), 2, two element tuples inside the tuple or the list is at least two, otherwise an error occurs

3, the user Fromkeys method to create a dictionary, the first

Code:

12 dict.fromkeys(("a""b"), 1)printx

Output:

{' A ': 1, ' B ': 1}

The first argument can be a list or tuple, the value of which is key, the second parameter is the value of all keys

A Dictionary of Python

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.