Python Data Type-dictionary-016

Source: Internet
Author: User

A, Dictionary (dictionary)

1. The dictionary (dictionary) is another very useful built-in data type in Python.

2, the list is an ordered combination of objects, the dictionary is an unordered collection of objects. The difference between the two is that the elements in the dictionary are accessed by keys, not by offsets.

3. The dictionary is a type of mapping, and the dictionary is identified with "{}", which is an unordered key (key): The value pair collection.

4. Keys (key) must use the immutable type.

5. In the same dictionary, the key must be unique.

Second, examples

#!/usr/bin/python3

Dict = {}

dict[' One ' = "1-Rookie 1"

DICT[2] = "2-Rookie 2"

tinydict = {' name ': ' Runoob ', ' Code ': 1, ' site ': ' www.runoob.com '}

Print (dict[' one ') # output key is ' one ' value

Print (dict[2]) # Value for Output key 2

Print (tinydict) # Output a complete dictionary

Print (Tinydict.keys ()) # Output all keys

Print (Tinydict.values ()) # Outputs all values

The result of the above example output:

1-Rookie 1
2-Rookie 2
{' name ': ' Runoob ', ' site ': ' www.runoob.com ', ' Code ': 1}
Dict_keys ([' Name ', ' site ', ' Code '])
Dict_values ([' Runoob ', ' www.runoob.com ', 1])

The constructor Dict () can build the dictionary directly from the key-value pair sequence as follows:

Instance

>>>dict (' Runoob ', 1), (' Google ', 2), (' Taobao ', 3)])

{' Taobao ': 3, ' Runoob ': 1, ' Google ': 2}

>>> {x:x**2 for x in (2, 4, 6)}

{2:4, 4:16, 6:36}

>>> dict (runoob=1, google=2, taobao=3)

{' Taobao ': 3, ' Runoob ': 1, ' Google ': 2}

In addition, the dictionary type has some built-in functions, such as clear (), keys (), values (), and so on.

Attention:

(1) A dictionary is a type of mapping whose elements are key-value pairs.

(2) The dictionary keyword must be immutable and cannot be duplicated.

(3) Create an empty dictionary using {}.

Python Data Type-dictionary-016

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.