Python's Strongest King (8)--dictionary (dictionary)

Source: Internet
Author: User
Tags shallow copy

1.Python dictionary (Dictionary)

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

each key value of the dictionary (key=>value) pair with a colon (:) split, Each pair is separated by a comma (,) , and the entire dictionary is included in curly braces ({}) , The format is as Follows:

D = {key1:value1, key2:value2}

the key must be unique, but the value does not have to Be.

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

1.1 Creating a dictionary

Example 1

D = {" demacia Force "" Galen  " " Darbond Explorer "  nerf "= {" night Hunter "" wei en " }

1.2 Accessing values in the dictionary

Example 2:

#!/usr/bin/env python#-*-coding:utf-8-*-#@Time: 2016/9/12 22:17#@Author: WwyxD = {"the power of Demacia":"Galen","Darbond":"nerf",}name= {"Night Hunter": 2, 2:"oh, Viv ."}Print "the name of the output Demacia force:", d["the power of Demacia"]Print "output Ice Shooter's name", d["Ice Shooter"]#no corresponding value throws an exception

Example 2 run Results

output Demacia name: Galen Traceback (most Recent called last): output ice Shooter's name   " e:/python/hello/untitled3/dictionary.py "  in <module>    print" output ice shooter's name ",  d["  Ice shooter "#  No corresponding value throws exception '\xe5\xaf\x92\xe5\x86\xb0\xe5\xb0\x84\ xe6\x89\x8b'

Note: if the dictionary does not have a corresponding key value, it throws an exception, as the previous example runs the result

1.3 Adding elements to a dictionary

Add new content to a dictionary by adding new key / value pairs, Modifying or deleting existing key / value pairs

Example 3

#!/usr/bin/env python#-*-coding:utf-8-*-#@Time: 2016/9/12 22:17#@Author: WwyxD = {"the power of Demacia":"Galen","Darbond":"nerf",}name= {"Night Hunter": 2, 2:"oh, Viv ."}Print "the name of the output Demacia force:", d["the power of Demacia"]d["Ice Shooter"] ="Ash"  #Add new DataPrint "output Ice Shooter's name", d["Ice Shooter"]#no corresponding value throws an exception

Example 3 runs as follows

Output Demacia name of the force: Galen output ice Shooter's name Ash

1.4 Deleting a dictionary element

Example 4:

#!/usr/bin/env python#-*-coding:utf-8-*-#@Time: 2016/9/12 22:17#@Author: WwyxD = {"the power of Demacia":"Galen","Darbond":"nerf",}name= {"Night Hunter": 2, 2:"oh, Viv ."}Print "the name of the output Demacia force:", d["the power of Demacia"]d["Ice Shooter"] ="Ash"  #Add new DataPrint "output Ice Shooter's name", d["Ice Shooter"]deld["Ice Shooter"]#Delete this valuePrint "deleted after output ice Shooter's name", d["Ice Shooter"]#no corresponding value throws an exception

Example 4 Run Results

  output Demacia The name of the force: Galen Traceback (most Recent called last): output ice shooter's name Ash File   " e:/python/hello/untitled3/dictionary.py  , line, in  <module> after deletion the name of the ice shooter  print   "  Delete the name of the ice shooter after deletion  , d["   ice shooter  ] #   No corresponding value throws exception  keyerror:  \xe5\xaf\x92\xe5 \x86\xb0\xe5\xb0\x84\xe6\x89\x8b   

2. Characteristics of dictionary keys

a Dictionary value can take any Python object without restriction , either as a standard object or as a user-defined one, but not a key.

Two important points to keep in mind:

1) The same key is not allowed to appear two Times. When created, if the same key is assigned a value of two times, the latter value is remembered, as in the following example:

Example 5

#!/usr/bin/env python#-*-coding:utf-8-*-#@Time: 2016/9/12 22:17#@Author: WwyxD = {"the power of Demacia":"Galen","Darbond":"nerf",}name= {"Night Hunter": 2, 2:"oh, Viv ."}Print "the name of the output Demacia force:", d["the power of Demacia"]d["Ice Shooter"] ="Ash"  #Add new DataPrint "output Ice Shooter's name", d["Ice Shooter"]d["Ice Shooter"] ="Catherine"  #Modifying DataPrint "modified to output ice Shooter's name", d["Ice Shooter"]#no corresponding value throws an exception

Example 5 Run Results

Output Demacia name of the power: Galen output ice shooter name Ash modified after output ice Shooter's name Catherine

2) The key must be immutable, so it can be used as a number, a string, or a tuple, so you can't use a list .

Example 6

#!/usr/bin/env python#-*-coding:utf-8-*-#@Time: 2016/9/12 22:17#@Author: WwyxName = {("Night Hunter","oh, Viv ."): 2, 2:"oh, Viv ."}Print "the output tuple is the name of (' night Hunter ', ' Vivian '):", name[("Night Hunter","oh, Viv .")]

Example 6 Run Results

The output tuple is the name of (' night Hunter  ' Vivian '): 2

Dictionary built-in functions & Methods

The Python dictionary contains the following built-in Functions:

Serial Number Functions and descriptions
1 CMP (dict1, Dict2)
Compares two dictionary Elements.
2 Len (dict)
Calculates the number of dictionary elements, that is, the total number of keys.
3 STR (dict)
The output dictionary is a printable string Representation.
4 Type (variable)
Returns the type of the variable entered and returns the dictionary type if the variable is a dictionary.

The Python dictionary contains the following built-in Methods:

Serial Number Functions and descriptions
1 Radiansdict.clear ()
Delete all elements in a dictionary
2 Radiansdict.copy ()
Returns a shallow copy of a dictionary
3 Radiansdict.fromkeys ()
Create a new dictionary with the keys to the dictionary in sequence seq, val is the initial value corresponding to all keys in the dictionary
4 Radiansdict.get (key, Default=none)
Returns the value of the specified key if the value does not return the default value in the dictionary
5 Radiansdict.has_key (key)
Returns False if the key returns true in the dictionary Dict
6 Radiansdict.items ()
Returns an array of traversed (key, Value) tuples as a list
7 Radiansdict.keys ()
Returns a dictionary of all keys in a list
8 Radiansdict.setdefault (key, Default=none)
Similar to get (), but if the key does not exist in the dictionary, the key is added and the value is set to default
9 Radiansdict.update (dict2)
Update the Key/value pairs of the dictionary dict2 to the Dict
10 Radiansdict.values ()
Returns all values in the dictionary as a list

Python's Strongest King (8)--dictionary (dictionary)

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.