d = {'key':'value'}
d1 = {'1':1,'2':2,'name':'zhl','seq':[1,2,3]}
print d.get('key','not found')
print d1.get(1,'not found')
print d1.get('seq',[2,3])
print d1.get(2,['a','b','c'])
print d1.pop('1',None)
print d1.pop(1,None)
print d1
d2 = {'1':1,'2':2,'3':3}
d2.setdefault('1',2)
d2.setdefault('4',4)
print d2
data = dict(red=1,green=2,blue=3)
print data
the_keys = ['a','b','c','d','e','f','g','h','i']
the_values = [1,2,3,4,5,6,7,8,9]
data1 = dict(zip(the_keys,the_values))
print "zip=",zip(the_keys,the_values)
print "data1=",data1
import itertools
data2 = dict(itertools.izip(the_keys,the_values))
print data2
data3 = dict({'12ba':49,'for':23,'orf':42},rof=41,fro=97,orf='00')
print data3
key_seq = [1,2,3,4,5,6,7,8,9,10]
print dict.fromkeys(key_seq,'HELLO')
def dictFromList(keysAndValues):
return dict(zip(keysAndValues[::2],keysAndValues[1::2]))
testList1 = [1,2,3,4,5,6,7,8,9,10]
print dictFromList(testList1)
testList2 = [1,'a',2,'b',3]
print dictFromList(testList2)
'''
1、可扩展为对所有可迭代对象进行处理,方法1仅针对可切片的序列进行处理
2、yield关键字关于生成器的语法需单独掌握
'''
def pairwise(iterable):
itnext = iter(iterable).next
while True:
yield itnext(),itnext()
def dictFromSeq(seq):
return dict(pairwise(seq))
print dictFromSeq('Hello,World')
def sub_dict(somedict,somekeys,default=None):
return dict([(k,somedict.get(k,default)) for k in somekeys])
dict1 = {1:'1',2:'b',3:'c','4':['a','b','c']}
keyss = [1,2,3,4]
dictGet = sub_dict(dict1,keyss)
for key in dictGet.keys():
if not dictGet[key]:
del dictGet[key]
print dictGet
def sub_dict_remove(somedict,somekeys,default=None):
return dict([(k,somedict.pop(k,default)) for k in somekeys])
'''
注意原始字典中多个键对应的值相等的情况
'''
def invert_dict(d):
return dict([(v,k) for k,v in d.iteritems()])
dd = {1:'a',2:'b',3:'c',4:'d'}
print invert_dict(dd)
from itertools import izip
def invert_dict_1(d):
return dict(izip(d.itervalues(),d.iterkeys()))
print invert_dict_1({'a':1,'b':2})
dd1 = {}
key1 = 'aa'
print dd1.setdefault(key1,[])
print dd1.setdefault('key2',[]).append(1)
print dd1.setdefault('key3',['aa']).extend(['1','2','3'])
print dd1
dd2 = {}
dd2.setdefault('key4',{})['value1'] = 'value1'
print dd2
animals = []
def deal_with_a_cat():
print "meow"
animals.append('cat')
def deal_with_a_dog():
print "bark"
animals.append('dog')
def deal_with_a_bear():
print "watch out for the *HUG"
animals.append('bear')
tokenDict = {
"cat":deal_with_a_cat,
"dog":deal_with_a_dog,
"bear":deal_with_a_bear
}
words = ['cat','dog','bear']
for word in words:
tokenDict[word]()
print animals
a0 = dict.fromkeys(xrange(10))
b0 = dict.fromkeys(xrange(5,15))
a = dict.fromkeys(xrange(10),'1')
b = dict.fromkeys(xrange(5,15),'2')
union = dict(a,**b0)
print union
print dict({'a':'a','b':'b','c':'c'},a='1',b='2')
if len(a) < len(b0):
inter = dict.fromkeys([x for x in a if x not in b0])
else:
inter = dict.fromkeys([x for x in b0 if x not in a])
print 'inter=',inter