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

WBOY
Release: 2016-06-10 15:04:45
Original
1452 people have browsed it

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 
Copy after login

2.clear()方法

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

使用方式:

dictionary_name.clear()
Copy after login

3,copy方法

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

dictionary_targetname = dictionary_sourcenme.copy() 
Copy after login

4,fromkeys()方法

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

dictionary_name.fromkeys([key1,key2,...],(default_value)) 
Copy after login

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'} 
Copy after login

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

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!