Detailed description of basic operations on Python dictionaries and dictionaries, and operations on python dictionaries

Source: Internet
Author: User

Detailed description of basic operations on Python dictionaries and dictionaries, and operations on python dictionaries

This document describes the basic operations of the Python dictionary and dictionary. We will share this with you for your reference. The details are as follows:

A dictionary is a data structure referenced by a name or keyword. Its keys can be numbers, strings, and tuples. This type of structure is also called ing. The dictionary type is the only internal ing type in Python. The basic operations include:

(1)len(): Return the number of key-value pairs in the dictionary;
(2)d[k]: Return the value of the keyword pair;
(3)d[k]=v: Associate the value with key value k;
(4)del d[k]: Delete the key value k;
(5)key in d: Whether the key value is in d. True is returned; otherwise, False is returned.

I. Create a dictionary

1.1 create a dictionary directly

d={'one':1,'two':2,'three':3}print dprint d['two']print d['three']

Calculation Result:

=======RESTART: C:\Users\Mr_Deng\Desktop\test.py======={'three': 3, 'two': 2, 'one': 1}23>>>

1.2 create a dictionary through dict

# _ * _ Coding: UTF-8 _ * _ items = [('one', 1), ('two', 2), ('Three, 3 ), ('four', 4)] content in print U' items: 'print itemsprint U' creates a dictionary using dict and outputs the dictionary content: 'd = dict (items) print dprint U': 'print d ['one'] print d ['three ']

Calculation Result:

======= RESTART: C: \ Users \ Mr_Deng \ Desktop \ test. py = content in items: [('one', 1), ('two', 2), ('Three, 3 ), ('four ', 4)] Create a dictionary using dict and output the dictionary content: {'four': 4, 'three ': 3, 'two': 2, 'one ': 1} query the dictionary content: 13 >>>

Or use keywords to create a dictionary.

# _ * _ Coding: UTF-8 _ * _ d = dict (one = 1, two = 2, three = 3) print U: 'print dprint U': 'print d ['one'] print d ['three ']

Calculation Result:

======= RESTART: C: \ Users \ Mr_Deng \ Desktop \ test. py ====== output dictionary content: {'three ': 3, 'two': 2, 'one': 1} query dictionary content: 13 >>>

Ii. format the dictionary string

# _*_ coding:utf-8 _*_d={'one':1,'two':2,'three':3,'four':4}print dprint "three is %(three)s." %d

Calculation Result:

=======RESTART: C:\Users\Mr_Deng\Desktop\test.py======={'four': 4, 'three': 3, 'two': 2, 'one': 1}three is 3.>>>

Iii. dictionary Methods

3.1Clear Function: Clear all items in the dictionary

# _*_ coding:utf-8 _*_d={'one':1,'two':2,'three':3,'four':4}print dd.clear()print d

Calculation Result:

=======RESTART: C:\Users\Mr_Deng\Desktop\test.py======={'four': 4, 'three': 3, 'two': 2, 'one': 1}{}>>>

See the following two examples.

3.1.1

# _*_ coding:utf-8 _*_d={}dd=dd['one']=1d['two']=2print ddd={}print dprint dd

Calculation Result:

=======RESTART: C:\Users\Mr_Deng\Desktop\test.py======={'two': 2, 'one': 1}{}{'two': 2, 'one': 1}>>>

3.1.2

# _*_ coding:utf-8 _*_d={}dd=dd['one']=1d['two']=2print ddd.clear()print dprint dd

Calculation Result:

=======RESTART: C:\Users\Mr_Deng\Desktop\test.py======={'two': 2, 'one': 1}{}{}>>>

3.1.2 The only difference with 3.1.1 is the clearing of dictionary d, 3.1.1Associate d with a new empty dictionary.This method has no effect on the dictionary dd. Therefore, after the dictionary d is left empty, the value in the dictionary dd remains unchanged. But in 3.1.2The clear method clears the content in dictionary d., Clear is a method of in-situ operations, so that all content in d is set to null, so that the space pointed to by dd is also set to null.

3.2Copy Function: Returns a new dictionary with the same key value.

# _ * _ Coding: UTF-8 _ * _ x = {'one': 1, 'two': 2, 'three ': 3, 'test': ['A ', 'B', 'C']} print U' initial X dictionary: 'print xprint U' X copied to Y: 'y = x. copy () print u'y dictionary: 'print yy ['three '] = 33 print U' modify the value in Y and observe the output: 'print yprint xprint U' deletes values in Y and observes that 'y ['test'] is output. remove ('C') print yprint x

Calculation Result:

======= RESTART: C: \ Users \ Mr_Deng \ Desktop \ test. py = initial X dictionary: {'test': ['A', 'B', 'C'], 'three ': 3, 'two': 2, 'one': 1} X copied to Y: Y dictionary: {'test': ['A', 'B', 'C'], 'one': 1, 'three ': 3, 'two': 2} modify the value in Y and observe the output: {'test': ['A',' B ', 'C'], 'one': 1, 'three ': 33, 'two': 2} {'test': ['A',' B ', 'C'], 'three ': 3, 'two': 2, 'one': 1} Delete values in Y, observe the output {'test': ['A ', 'B'], 'one': 1, 'three ': 33, 'two': 2} {'test': ['A',' B '], 'Three ': 3, 'two': 2, 'one': 1 }>>>

Note:After the value is replaced in the copied copy, the original dictionary will not be affected. However, if the copy is modified, the original dictionary will also be modified.deepcopyThe function uses deep replication to copy all its values. This method can solve the problem of changing the original dictionary due to the copy modification.

# _ * _ Coding: UTF-8 _ * _ from copy import deepcopyx = {} x ['test'] = ['A', 'B', 'C ', 'D'] y = x. copy () z = deepcopy (x) print U' output: 'print yprint zprint U' output after modification: 'x ['test']. append ('E') print yprint z

Operation output:

======= RESTART: C: \ Users \ Mr_Deng \ Desktop \ test. py = output: {'test': ['A', 'B', 'C', 'D']} {'test ': ['A', 'B', 'C', 'D']} after modification, output: {'test': ['A', 'B', 'C ', 'D', 'E']} {'test': ['A', 'B', 'C', 'D']} >>>

3.3Fromkeys Function: Create a new dictionary using the given key. The default value of the key is None.

# _*_ coding:utf-8 _*_d=dict.fromkeys(['one','two','three'])print d

Operation output:

=======RESTART: C:\Users\Mr_Deng\Desktop\test.py======={'three': None, 'two': None, 'one': None}>>>

Or specify the default value.

# _*_ coding:utf-8 _*_d=dict.fromkeys(['one','two','three'],'unknow')print d

Calculation Result:

=======RESTART: C:\Users\Mr_Deng\Desktop\test.py======={'three': 'unknow', 'two': 'unknow', 'one': 'unknow'}>>>

3.4Get Function: Access dictionary members

# _*_ coding:utf-8 _*_d={'one':1,'two':2,'three':3}print dprint d.get('one')print d.get('four')

Calculation Result:

=======RESTART: C:\Users\Mr_Deng\Desktop\test.py======={'three': 3, 'two': 2, 'one': 1}1None>>>

Note: The get function can access keys that do not exist in the dictionary. If the key does not exist, None is returned.

3.5Has_key Function: Check whether the dictionary contains the given key.

# _*_ coding:utf-8 _*_d={'one':1,'two':2,'three':3}print dprint d.has_key('one')print d.has_key('four')

Calculation Result:

=======RESTART: C:\Users\Mr_Deng\Desktop\test.py======={'three': 3, 'two': 2, 'one': 1}TrueFalse>>>

3.6Items and iteritems Functions: Items returns all dictionary items in the list. The items in the list come from (Key, value). iteritems works similar to items, but returns an iterator object instead of a list.

# _*_ coding:utf-8 _*_d={'one':1,'two':2,'three':3}print dlist=d.items()for key,value in list:  print key,':',value

Calculation Result:

=======RESTART: C:\Users\Mr_Deng\Desktop\test.py======={'three': 3, 'two': 2, 'one': 1}three : 3two : 2one : 1>>>
# _*_ coding:utf-8 _*_d={'one':1,'two':2,'three':3}print dit=d.iteritems()for k,v in it:  print "d[%s]="%k,v

Calculation Result:

=======RESTART: C:\Users\Mr_Deng\Desktop\test.py======={'three': 3, 'two': 2, 'one': 1}d[three]= 3d[two]= 2d[one]= 1>>>

3.7Keys and iterkeys: Keys returns the keys in the dictionary in the form of a list, iterkeys return key iterator

# _ * _ Coding: UTF-8 _ * _ d = {'one': 1, 'two': 2, 'three ': 3} print dprint U' keys method: 'list = d. keys () print listprint U' \ niterkeys method: 'it = d. iterkeys () for x in it: print x

Calculation Result:

======= RESTART: C: \ Users \ Mr_Deng \ Desktop \ test. py = {'three ': 3, 'two': 2, 'one': 1} keys method: ['three', 'two ', 'one'] iterkeys method: threetwoone >>>

3.8Pop Function: Delete the keys corresponding to the dictionary.

# _*_ coding:utf-8 _*_d={'one':1,'two':2,'three':3}print dd.pop('one')print d

Calculation Result:

=======RESTART: C:\Users\Mr_Deng\Desktop\test.py======={'three': 3, 'two': 2, 'one': 1}{'three': 3, 'two': 2}>>>

3.9Popitem Function: Remove an item from the dictionary

# _*_ coding:utf-8 _*_d={'one':1,'two':2,'three':3}print dd.popitem()print d

Calculation Result:

=======RESTART: C:\Users\Mr_Deng\Desktop\test.py======={'three': 3, 'two': 2, 'one': 1}{'two': 2, 'one': 1}>>>

3.10Setdefault Function: Similar to the get method, get the value associated with the given key. You can also set the corresponding key value if the dictionary does not contain the given key.

# _*_ coding:utf-8 _*_d={'one':1,'two':2,'three':3}print dprint d.setdefault('one',1)print d.setdefault('four',4)print d

Calculation Result:

{'three': 3, 'two': 2, 'one': 1}14{'four': 4, 'three': 3, 'two': 2, 'one': 1}>>>

3.11Update function: Update another dictionary with one dictionary

# _*_ coding:utf-8 _*_d={  'one':123,  'two':2,  'three':3  }print dx={'one':1}d.update(x)print d

Calculation Result:

=======RESTART: C:\Users\Mr_Deng\Desktop\test.py======={'three': 3, 'two': 2, 'one': 123}{'three': 3, 'two': 2, 'one': 1}>>>

3.12Values and itervalues Functions: Values returns the value in the dictionary in the form of a list. itervalues returns the worthy iterator. Because the value in the dictionary is not unique, the list can contain repeated elements.

# _*_ coding:utf-8 _*_d={  'one':123,  'two':2,  'three':3,  'test':2  }print d.values()

Calculation Result:

=======RESTART: C:\Users\Mr_Deng\Desktop\test.py=======[2, 3, 2, 123]>>>

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.