13. Python Dictionary

Source: Internet
Author: User
Tags delete key shallow copy

Pythondictionary (Dictionary)

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

Each key value of the dictionary is key=>value with a colon : Split, with a comma, split between each key-value pair, and the entire dictionary is enclosed in curly braces {}, as shown in the following format:

D = {key1:value1, key2:value2}

The key is generally unique, and the value does not need to be unique if the last key value pair is repeated instead of the previous one.

Instance

>>>dict = {'a':1,'b':2,'b':'3'};>>> dict['b']'3'>>>dict{'a':1,'b':'3'}

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

A simple Dictionary instance:

Dict = {'Alice'2341'Beth ' '9102'Cecil'3258' }

You can also create a dictionary like this:

Dict1 = {' abc ': 456};d ict2 = {' abc ': 123, 98.6:37};

Accessing values in the dictionary

Put the corresponding key into the familiar square brackets, the following example:

#!/usr/bin/python dict= {'Name':'Zara',' Age':7,'Class':' First'}; Print"dict[' Name ']:", dict['Name'];p rint"dict[' age ']:", dict[' Age'];

Execution results

dict['Name':  zaradict['age':  7 

If the data is accessed using a key that is not in the dictionary, the output error is as follows:

 #!/usr/bin/python dict  = { " name   ": "  Span style= "COLOR: #800000" >zara   ",   age   ":  7 ,  " class   ": "  first   " }; Print   dict[' Alice ':   ", Dict["  alice  " Span style= "COLOR: #800000" > "]; 

Execution results

Dict[' Alice ': Traceback (most recent call last):  File "test.py", line 5, <module>    print "dict[' Alice ']: ", dict[' Alice ']; Keyerror: ' Alice '

Modify Dictionary

The way to add new content to a dictionary is to add a new key/value pair, modify or delete an existing key/value pair as follows:

#!/usr/bin/python dict = {' Name ': ' Zara ', ' age ': 7, ' Class ': ' First '}; Dict[' age '] = 8; # Update existing entrydict[' School '] = "DPS School"; # ADD new entry  print "dict[' age '):", dict[' age '];p rint "dict[' School ']:", dict[' School '];

Execution results

Dict[' age ':  8dict[' School ':  DPS School

Delete a dictionary element

The ability to delete a single element also clears the dictionary, emptying only one operation.

Show Delete a dictionary with the Del command, as in the following example:

#!/usr/bin/python#-*-coding:utf-8-*-dict = {' Name ': ' Zara ', ' age ': 7, ' Class ': ' First '}; Del dict[' Name ']; # Delete key is ' Name ' entry dict.clear ();     # Empty dictionary all Entries del dict;        # Delete the dictionary print "dict[' age ']:", dict[' age '];p rint "dict[' School ']:", dict[' School '];

However, this throws an exception because the dictionary no longer exists after Del:

dict['age ']:traceback (most recent call last):  "test.py " 8  in <module>    " ", dict[' age '  'type'object is unsubscriptable
Properties 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:

#!/usr/bin/python dict = {' name ': ' Zara ', ' age ': 7, ' name ': ' Manni '}; print "dict[' name ']:", dict[' name '];

Execution results

dict[' Name ']:  Manni

2) The key must be immutable, so it can be used as a number, string or tuple, so the list is not, the following example:

#!/usr/bin/python dict = {[' Name ']: ' Zara ', ' Age ': 7}; print "dict[' name ']:", dict[' name '];

Execution Result:

Traceback (most recent):  File "test.py", line 3, <module>    dict = {[' Name ']: ' Zara ', ' age ': 7};t Ypeerror:list Objects is unhashable

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 Dict.clear ()
Delete all elements in a dictionary
2 Dict.copy ()
Returns a shallow copy of a dictionary
3 Dict.fromkeys (seq[, Val])
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 Dict.get (Key, Default=none)
Returns the value of the specified key if the value does not return the default value in the dictionary
5 Dict.has_key (Key)
Returns False if the key returns true in the dictionary Dict
6 Dict.items ()
Returns an array of traversed (key, value) tuples as a list
7 Dict.keys ()
Returns a dictionary of all keys in a list
8 Dict.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 Dict.update (DICT2)
Update the key/value pairs of the dictionary dict2 to the Dict
10 Dict.values ()
Returns all values in the dictionary as a list
11 Pop (Key[,default])
Deletes the value of the dictionary given key key, and returns the value to be deleted. The key value must be given. Otherwise, the default value is returned.
12 Popitem ()
Randomly returns and deletes a pair of keys and values in the dictionary.

13. Python 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.