Dictionary is a very important build-in
data structure in Python. It is an order-less key-value data store.
Dictionary creation
Dictionary can be created by assignment as
below:
mydict = { ‘key1’ :’value1’ ,
‘key2’ :’value2’ ,’key3’ :’value3’ }
key and value are separated by : , key-value pairs are separated by ;
dictionary can also be created vi
comprehension.
mydict = { id:str(id) for id in xrange(10)}
Note, dictionary is order-less, we can’t
assume it is stored by some order, in fact, it is stored by key’s hash value.
Dictionary access
Dictionary’s value can be access by it’s
key as
Value ---- mydict[key].
But if the key is
not in the dictionary, it will generate an Exception.
Dictionary’s value can be reset by
assignment
mydict[key]=value, if key is not in the
dictionary, it will create an new entry for it.
Dictionary element delete
The key-value pair can be deleted as
Dictionary’s key-value pair can be traversed
by for in statement
for key in mydict:
print
mydict[key]
it can be also traversed by items()
function which will return the key-value list.
for (key,value) in mydict.items():
print
key, value
the traversal of dictionary can also be
achived by iteritems(), iterkeys(), itervalues(), they are the iterators.
Some other common functions for dictionary
keys() and values()
the function will return a list of keys and
values. Note the order can’t be assumed.
get()
When you access the dictionary by
mydict[key], if the key is not in the dictionary, it will raise exception, a
safer way is to use
dict.get[key,default]
It will return the value of the key or
default if key not existing
update()
the dictionary can update by another
dictionary.
mydict1.update(mydict2)
if mydict2’ s key in mydict1, mydict1’ s value will be replace by mydict2
if mydict2’ s key not in mydict1, mydict1’ s key-value pair will be inserted.
Dictionary’s copy
There are two types of copy
- Shallow copy: it will copy by reference or pointer
- Deep copy: it will copy the exact value
In other words, when you do shallow copy
from a to b, when you changed the value in a, b’s value may be changed as well,
but if it is a deep copy, the value won’t be impacted.
import copy
mydict = {‘a’:[1,2,3,4]}
shallowdict = copy.copy(mydict)
deepdict = copy.deepcopy(mydict)
shallowdict now is {'a': [1, 2, 3, 4]}
deepdict now is {'a': [1, 2, 3, 4]}
deepdict['a'][0]=0 --- set the deep copy dictionary value
deepdict
now is {'a': [0, 2, 3, 4]}
mydict
not changed {'a': [1, 2, 3, 4]}
shallowdict['a'][0]=0 -- set the shallow copy dictionary value
mydict
changed {'a': [0, 2, 3, 4]}
Sort the dictionary
We may sort the dictionary by sort and
lambda
#Sort by key
sort(dict.items(), key=lambda d:d[0])
#Sort by value
sort(dict.items(), key=lambda d:d[1])
No comments:
Post a Comment