字典数据类型-字典常见操作

#1.1从字典里取值,不抛出异常
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)  #如果是d1.pop(1)将抛出KeyError异常
print d1

#1.2给字典新加一个条目,若存在则不做操作,若没有则赋值
d2 = {'1':1,'2':2,'3':3}
d2.setdefault('1',2)  #不会改变字典d2['1']的值
d2.setdefault('4',4)  #新增d2['4'] = 4
print d2  #{'1': 1, '3': 3, '2': 2, '4': 4}

#1.3使用dict函数创建字典
#键是标识符,不能是默认关键字、数字开头的标识符
data = dict(red=1,green=2,blue=3)  #{'blue': 3, 'green': 2, 'red': 1}
#data = dict(for=4,12red=2)  #错误的定义方式
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) #[('a', 1), ('b', 2), ('c', 3), ('d', 4), ('e', 5), ('f', 6), ('g', 7), ('h', 8), ('i', 9)]
print "data1=",data1 #{'a': 1, 'c': 3, 'b': 2, 'e': 5, 'd': 4, 'g': 7, 'f': 6, 'i': 9, 'h': 8}

#the_keys,the_values为大数据量,通过tertools模块来提高处理速度
import itertools
data2 = dict(itertools.izip(the_keys,the_values))
print data2

#dict调用基于位置的参数和关键参数,若关键参数值和位置参数冲突,则关键参数生效。
data3 = dict({'12ba':49,'for':23,'orf':42},rof=41,fro=97,orf='00')
print data3 #{'for': 23, '12ba': 49, 'orf': '00', 'fro': 97, 'rof': 41}

#创建字典,键对应的都是同一个值
key_seq = [1,2,3,4,5,6,7,8,9,10]
print dict.fromkeys(key_seq,'HELLO') #{1: 'HELLO', 2: 'HELLO', 3: 'HELLO', 4: 'HELLO', 5: 'HELLO', 6: 'HELLO', 7: 'HELLO', 8: 'HELLO', 9: 'HELLO', 10: 'HELLO'}

#1.4将列表元素交替作为键和值来创建字典
#方法1
def dictFromList(keysAndValues):  #keysAndVlaues元素个数为单数,最后一个键值将被舍弃;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: 'a', 2: 'b'}

#方法2
'''
1、可扩展为对所有可迭代对象进行处理,方法1仅针对可切片的序列进行处理
2、yield关键字关于生成器的语法需单独掌握
'''
def pairwise(iterable):  
    itnext = iter(iterable).next
    while True:
        yield itnext(),itnext()  #yield为生成器,生成器的语法规则?

def dictFromSeq(seq):
    return dict(pairwise(seq))

print dictFromSeq('Hello,World')


#1.5获取字典的一个子集
#1.5.1不改动原字典
def sub_dict(somedict,somekeys,default=None):
    return dict([(k,somedict.get(k,default)) for k in somekeys]) 
###########################################
#return dict([(k,somedict.get(k,default)) for k in somekeys if k in somedict])
###########################################

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  #{1: '1', 2: 'b', 3: 'c'}

#1.5.2从原字典删除那些符合条件的条目
def sub_dict_remove(somedict,somekeys,default=None):
    return dict([(k,somedict.pop(k,default)) for k in somekeys])

#1.6反转字典
'''
注意原始字典中多个键对应的值相等的情况
'''
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) #{'a': 1, 'c': 3, 'b': 2, 'd': 4}

#性能优化:
from itertools import izip
def invert_dict_1(d):
    return dict(izip(d.itervalues(),d.iterkeys()))

#test
print invert_dict_1({'a':1,'b':2})


#1.7字典的一键多值
#1.7.1通过设置的字典值为列表实现
dd1 = {}
key1 = 'aa'
print dd1.setdefault(key1,[]) #setdefault函数返回字段的值
print dd1.setdefault('key2',[]).append(1)
print dd1.setdefault('key3',['aa']).extend(['1','2','3'])
print dd1

#1.7.2通过设置字典的键值为字典实现
dd2 = {}
dd2.setdefault('key4',{})['value1'] = 'value1'
print dd2

#1.8使用字典分派方法和函数(case语句)
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

#1.9字典键的交集与并集 
a0 = dict.fromkeys(xrange(10))
b0 = dict.fromkeys(xrange(5,15))
a = dict.fromkeys(xrange(10),'1')  #xrange(10) 0~9  {0: '1', 1: '1', 2: '1', 3: '1', 4: '1', 5: '1', 6: '1', 7: '1', 8: '1', 9: '1'}
b = dict.fromkeys(xrange(5,15),'2') #xrange(5,15) 5~14

#并集
union = dict(a,**b0) #{0: '1', 1: '1', 2: '1', 3: '1', 4: '1', 5: None, 6: None, 7: None, 8: None, 9: None, 10: None, 11: None, 12: None, 13: None, 14: None}
print union

print dict({'a':'a','b':'b','c':'c'},a='1',b='2') #生成字典后,关键字参数会覆盖原字典中定义的值{'a': '1', 'c': 'c', '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

你可能感兴趣的:(python基础入门)