A brief introduction to Python dictionaries and detailed usage _python

Source: Internet
Author: User
Tags delete key shallow copy
#!/usr/bin/env python
#-*-coding:utf-8-*-"" "


The old rules of the following method environment 2.7.x, please 3.x above version of the Friends remember format print (output in parentheses)

The basic composition and usage of a dictionary

Dict = {Key:value}
dict[Key] = value

First of all, the dictionary is composed of key key and value one by one to form the basic structure of the dictionary

Key key cannot be named by list, Dict dictionary, etc.

Key is a unique property and can be called one-to-one service, key is the same but only output one

Value values can be named by one or more elements, not unique attributes, and can be called a One-to-many service

It is important that the dictionary is unordered.

Here's how to use the dictionary:

' "' #dic ={} Initializes a dictionary Dic_samekey = {" A ": None," a ": None," B ": None," B ": none} #key相同的情况 print Dic_samekey Dic_morevalue = {" A " : ["0", "1", "2"], "B": {"C": 0, "D": 1, "E": 2}, "T":(0,1,2)} #value一对多的特性 print Dic_morevalue #这时候看到多value很头疼了吧怎么取也来学习下, # In fact, the value of my name has been marked well subscript is also the default sort, the dictionary is unordered to remind #dict [key] = value so you can name a dictionary also can take a desired value print dic_morevalue["a"][0],dic_ Morevalue["A"][1],dic_morevalue["a"][2] print dic_morevalue["B" ["C"],dic_morevalue["B"] ["D"],dic_morevalue["B"]
["E"] #多字典用法可以构造多级选择 print dic_morevalue["T"][0],dic_morevalue["T"][1],dic_morevalue["T"][2] #快速获取字典所有的key方法及类型 Print Dic_morevalue.keys (), type (Dic_morevalue.keys ()) #返回的类型是list列表 #快速获取字典所有的value方法及类型 print Dic_morevalue.values (), type (Dic_morevalue.values ()) #也是list列表 #copy顾名思义拷贝 (shallow copy) is commonly known as assignment dic_test = dic_morevalue.copy () dic = dic_test Print Dic_ Test #clear同意思清除, in which all elements in the dictionary are emptied of print dic_morevalue.clear () #has_key用来判断字典内有无这个key键, and the Boolean type is returned as TRUE or false print Dic_test.has_key ("B") #get也可以用这个方法来判断字典内有无此key键, which returns the default value of None print dic_tes when there is no keyT.get ("K") #pop用来移除字典的某个key及其value B = Dic_test.pop ("b") print Dic_test,u "Remove B:", b #item () method to form a tuple of each pair of keys and value in the dictionary.
And put these tuples back in the list. item = Dic_test.items () print item #update可以把两个字典合并到其中用update的字典内 Dic2 = {"J": "Nice"} dic_test.update (dic2) Print dic_tes T #fromkeys从keys键队列中统一命名value值 if not set is none seq = [' name ', ' age ', ' job '] print dic_test.fromkeys (seq) Print Dic_
 Test.fromkeys (seq, "guess") #统一命名为guess

Let's look at the use of the dictionary below:

First, create a dictionary

The dictionary consists of a pair of keys and corresponding values. Dictionaries are also referred to as associative arrays or hash tables. The basic syntax is as follows:

dict = {'Alice': '2341', 'Beth': '9102', 'Cecil': '3258'}

You can also create a dictionary like this:

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

Attention:

Each key is separated from the value by a colon (:), each pair is separated by commas, and the whole is enclosed in curly braces ({}).
The key must be unique, but the value is not necessary.
Values can take any data type, but must be immutable, such as strings, numbers, or tuples.

Second, access to the dictionary value

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

#!/usr/bin/python

dict = {' Name ': ' Zara ', ' age ': 7, ' Class ': ' A ';

print "dict[' name ']:", dict[' name ';
Print "dict[' age ']:", dict[' age ';
#以上实例输出结果:
 

#dict [' Name ']: Zara
#dict [' Age ']: 7



If you use a key that is not in the dictionary to access the data, the error is printed as follows:

#!/usr/bin/python

dict = {' Name ': ' Zara ', ' age ': 7, ' Class ': ' A ';

Print "dict[' Alice ']:", dict[' Alice '];

#以上实例输出结果:

#dict [' Zara ']:
#Traceback (most recent call last):
# File "test.py", line 4, in <module>
   #  print "dict[' Alice ']:", dict[' Alice '];
#KeyError: ' Alice ' [/code]

Iii. Modifying the Dictionary

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

#!/usr/bin/python

dict = {' Name ': ' Zara ', ' age ': 7, ' Class ': ' A ';

dict[' age ' = 8; # Update existing entry
dict[' School ' = ' DPS School '; # Add new entry

print "dict[' Age": ", dict[' age '];
Print "dict[' School ']:", dict[' School '];
#以上实例输出结果:
#dict [' Age ']: 8
#dict [' School ']: DPS School

Iv. Delete dictionary elements

Can delete a single element can also empty the dictionary, empty only one operation.

Display deletes a dictionary with the DEL command, as follows:

#!/usr/bin/python

dict = {' Name ': ' Zara ', ' age ': 7, ' Class ': ' A ';

Del dict[' Name ']; # The DELETE key is the ' Name ' entry
dict.clear ();   # Empty dictionary All entries
del dict;    # Delete dictionary

print "dict[' age ']:", dict[' age ';
Print "dict[' School ']:", dict[' School '];
#但这会引发一个异常, because the dictionary no longer exists with Del:

dict[' age ':
#Traceback (most recent called last):
# File "test.py", line 8, in & lt;module>
#  print "dict[' Age": ", dict[' age '];
#TypeError: ' Type ' object is unsubscriptable

Characteristics of Dictionary Keys

Dictionary values can be used without restrictions on any Python object, either as a standard object or as a user-defined, but not a key.

Two important points to remember:

1 does not allow the same key to appear two times . When created, if the same key is assigned 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 ';
#以上实例输出结果:
#dict [' Name ']: Manni

2 The key must be immutable , so you can use a number, a string or a tuple to act, so use the list is not, the following example:

#!/usr/bin/python

dict = {[' Name ']: ' Zara ', ' Age ': 7};

print "dict[' name ']:", dict[' name ';
#以上实例输出结果:

#Traceback (most recent):
# File "test.py", line 3, in <module>
#  dict = {' Nam E ']: ' Zara ', ' Age ': 7};
#TypeError: List objects are unhashable

Vi. Dictionary built-in Functions & methods

The Python dictionary contains the following built-in functions:

1, cmp(dict1, dict2): compare two dictionary elements.
2, len(dict): calculate the number of dictionary elements, that is, the total number of keys.
3, str(dict): the output dictionary can be printed string representation.
4 type(variable): . Returns the type of variable entered, and returns the dictionary type if the variable is a dictionary.

The Python dictionary contains the following built-in methods:

1, radiansdict.clear (): Delete all elements in dictionary
2, radiansdict.copy (): return a shallow copy of a dictionary
3, Radiansdict.fromkeys (): Create a new dictionary with the keys in the sequence seq to do the dictionary, Val for the dictionary all keys corresponding to the initial value
4, radiansdict.get (Key, default= None): Returns the value of the specified key, if the value does not return a 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 a traversal (key, value) tuple array with List
7, Radiansdict.keys (): Returns a dictionary of all keys in a list
8, radiansdict.setdefault (Key, Default=none): is similar to get (), but if the key does not already exist in the dictionary, the key is added and the value is set to default
9, radiansdict.update (DICT2): updates the dictionary dict2 key/value pairs to Dict
10, radiansdict.values (): Returns all the values in the dictionary as a list

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.