5-- learning Python dictionary (dict)

Python dictionary mapping type, a "key on" (key-value) data structure.

key is any immutable type object, usually strings and numbers, can not be list (list can be changed).

value may be any type of data.

Dictionary can () and a pair of braces by creating an empty dictionary dict (d = {}), the key-value pairs with braces (:) are separated by between a plurality of key-value pairs (,) are separated.

 

Create an empty dictionary:

>>> d = {}

>>> d

{}

>>> d1 = dict()

>>> d1

{}

>>> d1 == d

True

 

It can be initialized by passing parameters.

Parameters passed in two forms: one is the sequence type data list or tuple, each element of which must also contains two sub-elements, in order to meet the key-value pairs; one is, name = value in the form of parameters.

>>> d = {'a':1,'b':2,'c':3}

>>> d

{'a': 1, 'b': 2, 'c': 3}

>>> d1 = dict(a=1,b=2,c=3)    #name=value形式的参数

>>> d1

{'a': 1, 'b': 2, 'c': 3}

>>> d2 = dict([('a',1),('b',2)])

>>> d2

{'a': 1, 'b': 2}

 

Create a dictionary for loop:

>>> dd = {x:x+x for x in range(5)}

>>> dd

{0: 0, 1: 2, 2: 4, 3: 6, 4: 8}

 

list can do value, but can not do key

>>> d = {'a':[1,2,3]}

>>> d

{'a': [1, 2, 3]}

>>> d1 = {[1,2,3],'a'}

Traceback (most recent call last):

  File "<pyshell#25>", line 1, in <module>

    d1 = {[1,2,3],'a'}

TypeError: unhashable type: 'list'

 

By accessing the dictionary key value, there are 2 ways:

D = dict >>> (A =. 1, B = 2, C =. 3 )

 >>> D 

{ ' A ' :. 1, ' B ' : 2, ' C ' :. 3 }

 >>> D [ ' B ' ]        # access to the values 'B'
 
2 

>>> d.get ( ' A ' )     # by a (key) method to access the value of GET
 
. 1 

>>> D [ ' C ' ] =. 5 

>>> D 

{ ' A ' :. 1, ' B ' :2, 'c': 5}

 

Dictionary change

D = dict >>> (A =. 1, B = 2, C =. 3 )

 >>> D 

{ ' A ' :. 1, ' B ' : 2, ' C ' :. 3 }

 >>> D [ ' B ' ] = 5     # modify the value of a key
 
>>> D 

{ ' a ' :. 1, ' B ' : 5, ' C ' :. 3 }

 >>> D [ ' D ' ] =. 7         # add a key on
 
>>> d

{'a':. 1, ' B ' :. 5, ' C ' :. 3, ' D ' :. 7 }

 >>> del D [ ' A ' ]         # delete a key-value pair
 
>>> D 

{ ' B ' :. 5, ' C ' :. 3, ' D ' :}. 7

 

sorted () all key dictionary as a list (or component) to sort

>>> d = dict(a=1,b=2,c=3,d=4)

>>> d

{'a': 1, 'b': 2, 'c': 3, 'd': 4}

>>> sorted(d)

['a', 'b', 'c', 'd']

 

Traversal key:

>>> for key in d:

print(key)

 

 

a

b

c

d

clear () can empty a dictionary:

 

fromkeys () to initialize the dictionary by a sequence:

>>> d={}

>>> d.fromkeys([1,2,3])

{1: None, 2: None, 3: None}

>>> d.fromkeys([1,2,3],1)

{1: 1, 2: 1, 3: 1}

 

update () to update the dictionary with a dictionary to another:

>>> x = d.fromkeys([1,2,3])

>>> x

{1: None, 2: None, 3: None}

>>> x.update({1:'a',2:'b'})

>>> x

{1: 'a', 2: 'b', 3: None}

 

The string dictionary for formatting function --format_map

>>> template = '''<html>

<head><title>{title}</title></head>

<body>

<h1>{title}</h1>

<p>{text}</p>

</body>'''

>>> data = {'title':'My Home Page','text':'Welcom to my home page'}

>>> print(template.format_map(data))

<html>

<head><title>My Home Page</title></head>

<body>

<h1>My Home Page</h1>

<p>Welcom to my home page</p>

</body>

 

copy method returns a new dictionary, this method of execution is a shallow copy, because the original value in itself.

>>> x = {'username':'admin','abc':['foo','bar','baz']}

>>> y = x.copy()

>>> y

{'username': 'admin', 'abc': ['foo', 'bar', 'baz']}

>>> y['abc'].remove('bar')

>>> y['username']='admin123'

>>> y

{'username': 'admin123', 'abc': ['foo', 'baz']}

>>> x

{'username': 'admin', 'abc': ['foo', 'baz']}

 

Shallow copy, when a copy of the replacement value, the original unaffected ( 'username' corresponding to the value). However, the copy of the modified value, but also the change in the original ( 'abc' change list) occurs.
To avoid the above situation, you can perform a deep copy . That also copy the values and all the values it contains.

>>> from copy import deepcopy

>>> d = {}

>>> d['names'] = ['alfred','bertrand']

>>> c = d.copy()

>>> e = deepcopy(d)

>>> d['names'].append('clive')

>>> c

{'names': ['alfred', 'bertrand', 'clive']}

>>> e

{'names': ['alfred', 'bertrand']}

Guess you like

Origin www.cnblogs.com/suancaipaofan/p/11069081.html