码迷,mamicode.com
首页 > 编程语言 > 详细

Python字典

时间:2017-06-29 00:50:06      阅读:175      评论:0      收藏:0      [点我收藏+]

标签:python

#!/usr/bin/env python

#coding:utf-8


info = {

    ‘name1‘: "jenkins",

    ‘name2‘: "docker",

    ‘name3‘: "elk",

    ‘name4‘: "zabbix"

}


#增加

info["name5"] = "redis"

print info


#删除

del info["name4"]

print info

info.pop("name2")  #标准删除资势

print info

info.popitem() #随机删除

print  info


#修改

info["name3"] = "python"

print info


#查询

print info

print info["name1"] #如果一个key不存在,就报错,get不会,不存在只返回None

print info.get("name1") #获取

print "name1" in info #标准用法,

print info.has_key("name1") #python2用法,python3里没有


#多级字典嵌套及操作

zhongguo = {

    "gz": {

        "tianhe": ["this is tianhe","youkongguolaiwan"],

        "yunxiu": ["this is yuexiu","youkongguolaiwan"],

    },

    "foshan": {

        "chancheng": ["this is chanchen","youkongguolaiwan"],

        "gaoli": ["this is gaoli","youkongguolaiwan"],

    }

}


print zhongguo

zhongguo["foshan"]["gaoli"][1] = "this is test"

print zhongguo

print zhongguo["foshan"]["gaoli"][1] == "this is test"



zhongguo.setdefault("jiangmen",{"www.baidu.com":[1,2]})#添加一个新的字典

print zhongguo


info2 = {

    ‘test1‘: "xiao ming",

    ‘test2‘: "xiao qiang",

    ‘test3‘: "xiao lso"

}


b = {

    ‘test1‘: "woqr",

    1: 3,

    2: 4

}

print info2

info2.update(b)  #更新并合并info

print info2


#把一个字典转成了一个列表

print info2.items()


print info

print dict.fromkeys([6,7,8],"test") #初始化一个字典

c = dict.fromkeys([6,7,8],[111,{"name":‘jesfw‘},222])

print c

c[7][1][‘name‘] = "Jack"

print c


for i in info:

    print i,info[i] #打印key,value


for k,v in info.items():

    print k,v


#上面这个比下面高效,通过循环通过key索引找出值















本文出自 “YHT的运维笔记” 博客,请务必保留此出处http://yht1990.blog.51cto.com/9014030/1942747

Python字典

标签:python

原文地址:http://yht1990.blog.51cto.com/9014030/1942747

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!