Getting Started with Python (vii) dict

Source: Internet
Author: User

Dict in Python is also known as an associative array or a hash table, which consists of a pair of keys and values.

1. Creation of dict: enclosed in {}, between key and value: Split, between each key-value pair, split

Dict1 = {' name ': ' Billy ', ' Age ': 28}print (dict1) >>> {' age ': +, ' name ': ' Billy '}

Note: Keys must be unique and must be immutable, such as strings, numbers, and tuples.

The value can be any type and can be modified arbitrarily.

2. Accessing elements in Dict: Access by key

Print (dict1[' name ']>>> billyprint (dict1[' age ')) >>> 28

However, if the key that is accessed does not exist, an exception is thrown

Print (dict1[' sex ') Traceback (most recent call last): File "<pyshell#4>", line 1, in <module> print (dict1[ ' Sex ']) keyerror: ' Sex '

To avoid this problem, we can use the Get method to judge

Value = dict1.get (' sex ') #此时value = Noneif Value:print (' The value of sex exist ') else:print (' The value of sex does Not exist ') >>> the value of sex does not exist

Traverse the entire dict

#method 1for K in Dict1:print (K, dict1[k]) >>>age 28name billy#method 2for (k,v) in Dict1.items (): Print (k, V) >>> age 28name billy#method 3for K in Dict1.keys (): Print (k, dict1[k]) >>>age 28name Billy

3. Add/Remove elements

#增加元素dict1 [' sex '] = ' male ' Print (Dict1) >>> {' Sex ': ' Male ', ' age ': +, ' name ': ' Billy '} #删除元素del dict1[' sex '] Print (Dict1) >>> {' Age ': ' Name ': ' Billy '} #如果要删除元素的键不存在, throw exception del dict1[' Sex ']traceback (most recent call Last): File "<pyshell#42>", line 1, in <module> del dict1[' sex ']keyerror: ' Sex ' #这个时候可以用到上面提到的get方法来判断键是否存在 , and then perform the delete operation if it exists!

Modifying the value of an element

dict1[' age ' = 25print (dict1) >>> {' Age ': ' Name ': ' Billy '}

4. Dict Other common methods:

1) Copy (): Copy all elements in Dict

Dict2 = Dict1.copy () print (dict2) >>> {' name ': ' Billy ', ' Age ': 25}

2) Clear (): Clears all elements in the Dict

Dict2.clear () print (Dict2) >>> {}

3) keys (): Returns all keys in Dict in a list

For k in Dict1.keys (): print (k) >>> Agename

4) VALUES (): Returns all values in Dict in a list

For V in Dict1.values (): Print (v) >>> 25billy

5) Len (): Gets the number of elements in the Dict

Print (len (dict1)) >>> 2

Dict is very useful in practical development, such as when we are writing HTTP service programs, we can store each field in the HTTP request header in Dict, which is very convenient to use.

Getting Started with Python (vii) dict

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.