Home  >  Article  >  Backend Development  >  python中字典dict常用操作方法实例总结

python中字典dict常用操作方法实例总结

WBOY
WBOYOriginal
2016-06-10 15:16:141434browse

本文实例总结了python中字典dict常用操作方法。分享给大家供大家参考。具体如下:

下面的python代码展示python中字典的常用操作,字典在python开发中有着举足轻重的地位,掌握字典操作相当重要

#创建一空字典
x = {}
#创建包含三个项目的字典
x = {"one":1, "two":2, "three":3}
#访问其中的一个元素
x['two']
#返回字典中的所有键列表
x.keys()
#返回字典中的所有值列表
x.values()
#添加一个新的项目
x["four"]=4
#修改一个字典项目
x["one"] = "uno"
#删除一个字典项目
del x["four"]
#复制一个字典到新的变量
y = x.copy()
#清除所有字典项目
x.clear()
#返回字典长度,项目个数
z = len(x)
#检测字典是否包含了指定的key
z = x.has_key("one")
#遍历字典中的key
for item in x.keys(): print item
#遍历字典中的值列表
for item in x.values(): print item
#使用if语句获取字典中相应的键值
if "one" in x:
  print x['one']
if "two" not in x:
  print "Two not found"
if "three" in x:
  del x['three']

希望本文所述对大家的Python程序设计有所帮助。

Statement:
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