| 
字典的内建方法:
x
马上注册,结交更多好友,享用更多功能^_^您需要 登录 才可以下载或查看,没有账号?立即注册  
 
 
 1.      fromkeys () 
 
 >>> dict1.fromkeys((1,2,3)) 
 
 {1: None, 2: None, 3: None} 
 
 >>>dict1.fromkeys((1,2,3),'number') 
 
 {1: 'number', 2: 'number', 3: 'number'} 
 
 >>> dict1.fromkeys((1,2,3),('one','two','three')) 
 
 {1: ('one', 'two', 'three'), 2: ('one','two', 'three'), 3: ('one', 'two', 'three')} 
 
   
 
 2. 访问字典的方法: 
 
  (1)keys: 
 
 >>> dict1 =dict1.fromkeys(range(5),'赞') 
 
 >>> dict1 
 
 {0: '赞', 1: '赞', 2: '赞', 3: '赞', 4: '赞'} 
 
 >>> for eachkey in dict1.keys(): 
 
        print(eachkey) 
 
 0 
 
 1 
 
 2 
 
 3 
 
 4 
 
 (2) values: 
 
 >>> for eachvalue indict1.values(): 
 
        print(eachvalue) 
 
 赞 
 
 赞 
 
 赞 
 
 赞 
 
 赞 
 
 (3) items () 
 
 >>> for eachitem in dict1.items(): 
 
        print(eachitem) 
 
  (0,'赞') 
 
 (1, '赞') 
 
 (2, '赞') 
 
 (3, '赞') 
 
 (4, '赞') 
 
   
 
 如果不知道字典中是否有此值,可以用in 或者 not in。 
 
 >>> 4 in dict1 
 
 True 
 
 >>> 5 in dict1 
 
 False 
 当数据规模很大的时候,字典和序列查找的效率有较大差别,字典高效。在字典里查找的是键,而在序列里查找的是元素的值而不是元素的索引号。 
 (4). 清空字典 clear ( ) 
 
 >>> dict1 
 
 {0: '赞', 1: '赞', 2: '赞', 3: '赞', 4: '赞'} 
 
 >>> dict1.clear() 
 
 >>> dict1 
 
 {} 
 
   
 
 (5). Copy() 
 
 >>> a ={1:'one',2:'two',3:'three'} 
 
 >>> b = a.copy() 
 
 >>> c = a 
 
 >>> c 
 
 {1: 'one', 2: 'two', 3: 'three'} 
 
 >>> b 
 
 {1: 'one', 2: 'two', 3: 'three'} 
 
 >>> id(a)       # a和c地址一样。 
 
 55314824 
 
 >>> id(b)       #a和b地址一样 
 
 55415880 
 
 >>> id(c) 
 
 55314824 
 
   
 
 (6) pop ( ) 
 
 >>> a.pop(2) 
 
 'two' 
 
 >>> a 
 
 {1: 'one', 3: 'three'} 
 
 >>> a.popitem()        #随机弹出字典元素 
 
 (1, 'one') 
 
   
 
 (7) setdefault ( ): 
 
 >>> a ={1:'one',2:'two',3:'three'} 
 
 >>> a 
 
 {1: 'one', 2: 'two', 3: 'three'} 
 
 >>> a.setdefault(4,'小白') 
 
 '小白' 
 
 >>> a 
 
 {1: 'one', 2: 'two', 3: 'three', 4: '小白'} 
 
  (8) update ( ) 
 
 >>> b = {'小白':'狗'} 
 
 >>> a.update(b) 
 
 >>> a 
 
 {1: 'one', 2: 'two', 3: 'three', 4: '小白', '小白': '狗'} 
 
 |