A Dictionary of Python

Source: Internet
Author: User

I. Introduction to the Dictionary

1. A dictionary is another mutable container model and can store any type of object.

2. Each key value of the dictionary key-value pairs with a colon : Split, each key-value pair is separated by commas, and the entire dictionary is included in the curly braces {}, as shown in the following format:D = { key1 : value1, key2 : value2 }

3. The dictionary is unordered

4. The key in the dictionary is unique, if key is already present, overwrite the value of key, and if key does not exist, insert a key value pair

5. The value can take any data type, but the key must be immutable, such as a string, a number, or a tuple

Second, the use of the dictionary

data = {' name ': ' Zhang San ',

' Age ': 18,

' Sex ': ' Woman '}

1. Increase

data[' email ']= ' [email protected] '

Data.setdefault (' age ', $) #setdefault这种方式, if key already exists, regardless of it, if key does not exist, add

2. Modifications

data[' sex ']= ' man '

3. Delete

Data.pop (' sex ') #指定的key来删除, key does not exist will error

del data[' sex '] #指定的key来删除, key does not exist will error

4. Take the value

data[' sex ']

Data.get (' sex1 ', ' haha ') #返回指定键的值 if the value does not return the default value in the dictionary (' haha ')

5. Other

Data.clear () #清空字典

Data.update (DATA2) #把字典2的键值对加入到字典里

Data.items () #以列表返回可遍历的 (key, value) tuple array

Data.keys () #以列表返回一个字典所有的键

Data.valus #以列表返回一个字典所有的值

Data.popitem () #随机返回并删除字典中的一对键和值

6. How to efficiently cycle a dictionary:

For k in data:

Print (K,data.get (k))

 

A Dictionary 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.