python 字典

(1)Properties:
No order, No repeat, implemented by hash_table

Note: key is immutable, it must can be hashed, so the type of key must be immutable, such as digit, string, or tuple.
dic = {'a':1 , 'b':2 , 'c': 3}, there is no order for the element, so dict[0] is in a SyntaxError.

but, initial dict, and print it, the print consequence may be different from the initialization order. (because of the function of hash_table).
dic.add['c'] = 4 ==> {'a':1 , 'b':2 , 'c': 4}
(2)common methods
items() ## # get all element one time, and return a list
iteritems() ##> return a iterator for the dict element
example:
>>> D.items() #all elements, using "for" traverse
[('a', 1), ('c', 3), ('b', 2), ('d', 4)] 
>>> D.iteritems() 
<dictionary-itemiterator object at 0x00000000026243B8>

(3)sort for dict(using build-in: sorted)
function prototype:sorted(dic,value,reverse)
eg. 1:
dic = {'a':31, 'bc':5, 'c':3, 'asd':4, '33':56, 'd':0}
print sorted(dic.iteritems(), key=lambda d:d[1], reverse = False ) 

#[('d', 0), ('c', 3), ('asd', 4), ('bc', 5), ('a', 31), ('33', 56)]

interpretation: 

>> Starting with Python 2.4, both list.sort() and sorted() added a key parameter

>> to specify a function to be called on each list element prior to making comparisons.


EG. 2:

>>> sorted(list(dic), key=lambda d:d[1], reverse=False)
Traceback (most recent call last):
File "<pyshell#36>", line 1, in <module>
sorted(list(dic), key=lambda d:d[1], reverse=False)
File "<pyshell#36>", line 1, in <lambda>
sorted(list(dic), key=lambda d:d[1], reverse=False)
IndexError: string index out of range
>>> sorted(list1) ##OK
(4)traverse dict
dic={'a':'12', 'we':'90', 'dd':'dd'}
for key in dic:
print key
EG. 2:
dic={'a':'12', 'we':'90', 'dd':'dd'}
for value in dic.values():
print value
(5)delete dict
del dic['a']
dic.clear()
del dic

(6)merge two dict

dict1.update(dict2)

http://www.cnblogs.com/dkblog/archive/2012/02/02/2336089.html

(7) create dict

  * directly

  * dict()

  * build-in function: fromkeys(seq[,value]):  dict1={}.fromkeys(('x','y'),-1)

  * create dict by two list:

>>> dt=dict(zip(keys,values))
>>> dt
{1: 'aa', 2: 'bb', 3: 'cc', 4: 'dd'}

原文地址:https://www.cnblogs.com/lifeinsmile/p/5405959.html