Maison  >  Article  >  développement back-end  >  python操作字典类型的常用方法(推荐)

python操作字典类型的常用方法(推荐)

WBOY
WBOYoriginal
2016-06-10 15:04:451456parcourir

has_key()方法可以检查字典中是否含有指定的键,如果有则返回True,否则就返回False。

语法格式:

dictionary_name.has_key(key) 

dict1 = {'01':'yangry','02':'weild','03':'hexh','04':'huangmg'}
print dict1.has_key('02')
print dict1.has_key('08') 

#result
True
False 

2.clear()方法

用于清除字典中所有的项,无返回值。

使用方式:

dictionary_name.clear()

3,copy方法

copy()方法返回一个具有相同键值对的新字典,格式如下:

dictionary_targetname = dictionary_sourcenme.copy() 

4,fromkeys()方法

使用给定的键来建立新的字典,每个键值对应的值为None。

dictionary_name.fromkeys([key1,key2,...],(default_value)) 

5,update()方法

格式:

update_dictionary.update(source_dictionary) 

mydict1 = {'1':'yy11','2':'yy22','3':'yy33'}
newdict = {'2':'success'} 

mydict1.update(newdict)
print mydict1 


#result
{'1': 'yy11', '3': 'yy33', '2': 'success'} 

以上这篇python操作字典类型的常用方法(推荐)就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持脚本之家。

Déclaration:
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn