Python course third week built-in data structure--dictionary

Source: Internet
Author: User
Tags iterable

dictionaries , unordered collections in python, key-value structures, access values by key, rather than relying on offsets or indexes to access Them. Here are some of the basic properties of the Dictionary:

    • The value of a dictionary can be any value, such as a number, a string, a list, a tuple, or even the dictionary itself.

    • The key of a dictionary must be a hash value

    • The key to the dictionary is unique

    • The dictionary does not have a slice operation and can only access value by key

    • The elements in the dictionary are stored in an unordered

    • variable-length, heterogeneous, arbitrary nesting

    • Object reference Table: uses the most optimized hashing algorithm to find the key, so the key search is very fast, and the dictionary stores the object reference (not the copy).


initialization of the dictionary :

D=dict () #空字典d ={} #空字典d ={' a ': ' b '} #单个键值对的字典d = Dict.fromkeys ([' a ', ' b ']) #会创建一个 {' a ': none, ' b ': none} dictionary d = dict (zip ( keylist, valuelist)) #多个键值对的字典, keylist and ValueList must be an iterative object

Subscript operation of the dictionary

d= {' a ': 1, ' b ': 2}>>>d[' a ']1>>>d[' a ']=123 #修改value =123>>>d{' a ': 123, ' b ':2}>>> d[ ' C '] = 345#key does not exist automatically creates a Key-value key value pair >>> d{' c ': 345, ' b ': 2, ' a ': 123}
>>> d[' D '] #当访问不存在的key时 returns a keyerror error traceback (most recent call last): File "<stdin>", line 1, in < Module>keyerror: ' d '


Dictionary Common Methods :

Increase

Update () #可接受一个dictionary, an iterative object consisting of a two-tuple , or a keyword argument as a function parameter, and then add the parameter to the dictionary of the calling Method.

Directly add the corresponding Key-value pair via key

SetDefault (k,[d]) #给字典增加一个元素, If k exists, returns the corresponding value v, does not exist, increases the K-D key value pair and returns D.

Examples are as Follows:

Through the update method:

>>>d={' a ': 1, ' b ': 2}>>>d.update (c=3) #给d增加一个键值对 ' c ': 3>>>d{' c ': 3, ' b ': 2, ' a ': 1}>> >d.update ([' F ', 4), (' g ', 5)]) #给d增加两个键值对, using a two-tuple structure to make the parameters of an iterative Object. >>> d{' c ': 3, ' b ': 2, ' F ': 4, ' a ': 1, ' G ': 5}>>>d.update ({' e ': 5}) #给d增加一个键值对, How to use a dictionary for parameters >>> d{ ' C ': 3, ' b ': 2, ' a ': 1, ' e ': 5, ' g ': 5, ' F ': 4}


To add a value by key

>>>d = {' a ': 1, ' b ': 2}>>>d[' c '] = 3 #此时d就是 {' a ': 1, ' b ': 2, ' C ': 3}


Through the SetDefault function

>>>d = {' a ': 1, ' b ': 2}>>>d.setdefault (' a ', 2) # returns the value corresponding to ' a ' 11>>> d.setdefault (' h ', 10) # Increase the key value in D to ' H ': 10 and return the value 1010>>> d{' c ': 3, ' b ': 2, ' a ': 1, ' e ': 5, ' g ': 5, ' H ': ten, ' F ': 4}


Delete

Pop (k,[d]) #根据给出的k, Delete k in the dictionary, and then return the k corresponding to v, if K does not exist, return the given default value d, if not given the default value, return Keyerror

Popitem () #在字典中随机取一个键值对 and then returns as a tuple that returns a keyerror if the dictionary is empty

Clear () #删除字典里面的全部元素

Del (d[key]) #del方法删除根据键删除对应的值, if key does not exist, the Keyerror error is Reported.

Example:

>>> d{' e ': 234,  ' i ': 555,  ' f ':  3,  ' G ': 333,  ' C ': 3,  ' a ': 123,  ' b ': 2}    #d原来的值 >> > d.pop (' e ')      #删除 ' e ': 234 key-value pairs and returns 234234>>> d.pop (' J ')      #删除不存在的键 ' J ', return keyerror error traceback  (most recent call last):file  "<stdin>",  line 1, in <module>KeyError:  ' J ' >>> d.pop (' J ', -1)      #删除不存在的键 ' J ', give default value-1, return default value -1>>> d.popitem ()       #返回键值对 (' i ',  555) >>>del (d[' e '] #不存在的键值对, Error. traceback  (most recent call last):file  "<stdin>",  line 1, in  <module>KeyError:  ' E ' >>>del (d[' a ']) #删除 ' a ' corresponding Value. >>>d{' b ': 2,  ' F ': 3,  ' I ': 555,  ' g ':  333} 

Change

Modify the corresponding value directly by key

Update () #根据给出的键来修改对应的值, key does not exist new key value pair

Examples are as Follows:

>>>d = {' a ': 1, ' b ': 2}>>>d[' a '] = 3>>>d{' b ': 2, ' a ': 3}>>>d.update (a=2) >>> d{' b ': 2 ', ' a ': 2}


Check

Access to the corresponding value via key

Get (k,[d]) #通过k来访问对应值, The corresponding value exists to return the corresponding value, does not exist to return the default value d, No default value is returned Empty. using the Get method to find the corresponding value can effectively avoid throwing a keyerror error when the value does not exist .

Examples are as Follows:

>>>d={' a ': 1, ' b ': 2}>>>d[' a ']1>>> d.get (' b ', 3) 2>>> d.get (' c ', 3) 3>>> D.get (' C ')

Dictionaries are also a type of sequence, so you can also apply some of the common methods of sequences, such as Len (d), which is the number of key-value pairs in a dictionary.


The traversal of a dictionary

Keys () #返回一个dict_keys可迭代对象, including all keys, so you can iterate through the dictionary in this way

Values () #返回一个dict_values可迭代对象, containing all of the value

Items () #返回一个dict_items (key-value key-value Pairs) iterate over an object, and a tuple of key-value pairs can be removed through a for loop or other iteration tool

Fromkeys (iterable,value=none) #用于给字典初始化, with the object in Iterable as key, the default value is None

Examples are as Follows:

>>>d = {' a ': 1, ' b ':2}>>> d{' b ': 2, ' a ': 1}>>> for key in D.keys (): #通过键来遍历字典 ... print (key, ' = = ', D[key]) ... b = 2a = 1

In python2, the above method is used to traverse the dictionary to return a list of key lists, value lists, or Key-value pairs, but in python3, the iteration object is Returned. Reduced memory Footprint.


Sort the keys

Use the list transformation to return an iterative object, and then use the sorted method to sort by reading the key-value pair in the for Loop. Examples are as Follows:

>>> for key in sorted (list (d.keys ())): ... print (key, ' = = ', d[key]) ... a = 1b + 2

This section introduces a dictionary of one of Python's built-in types, a dictionary as an unordered collection of data stored in the form of Key-value pairs, fast searching, support for arbitrary nesting, growth and shortening as needed, and very flexible, so it is widely used in Python Development. therefore, the basic method of the dictionary to Practice repeatedly, requires proficiency.


This article is from the "no flying world" blog, Please be sure to keep this source http://hf1208.blog.51cto.com/8957433/1882311

Python course third week built-in data structure--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.