Python字典

       python内置映射类型字典(dict)是除列表(list)之外python之中最灵活的内置数据结构类型。列表是有序的对象结合,字典是无序的对象集合。两者之间的区别在于:字典当中的元素是通过键来存取的,而不是通过偏移存取。

      如果说列表是支持位置读取对象的引用数组,那么字典就是支持键读取无序对象的引用表。从本质上讲,字典是作为哈希表(支持快速检索的数据结构)来实现的。一开始很小,并根据要求而增长。此外,Python采用最优化的哈希算法来寻找键,因此搜索是很快速的。和列表一样字典存储的是对象引用。


字典的遍历
方法一:

dict = {"a" : "apple", "b" : "banana", "g" : "grape", "o" : "orange"}
for k in dict:
   print "dict[%s] =" % k,dict[k]
方法二:字典items()的使用

调用items()实现字典的遍历

dict = {"a" : "apple", "b" : "banana", "g" : "grape", "o" : "orange"}
for (k, v) in dict.items():
   print "dict[%s] =" % k, v
方法三:调用iteritems()实现字典的遍历
dict = {"a" : "apple", "b" : "banana", "g" : "grape", "o" : "orange"}
for k, v in dict.iteritems():
   print "dict[%s] =" % k, v
或
for (k, v) in zip(dict.iterkeys(), dict.itervalues()):
   print "dict[%s] =" % k, v
运行结果:
dict[a] = apple
dict[b] = banana
dict[o] = orange
dict[g] = grape


使用列表、字典作为字典的值

from random import randint
import time
num = randint(1,6)
list = []  
for i in range(1,num):
    t = int(round(time.time()*1000))
    hui = str(i)  
    hei = {"name"+hui:"jiekou"+hui,"data"+hui:{"value":[t,i]}}  
    list.append(hei)  
message = {"a":{"disku":32,"memu":37,"cpuu":0.2,"cput":100},"b":list}  
print message  
print message["a"]["disku"]  
print message["a"]["memu"]  
print message["a"]["cpuu"]  
print message["a"]["cput"]  
print message["b"][0]["data1"]["value"][0]

运行结果:
{'a': {'memu': 37, 'cput': 100, 'cpuu': 0.2, 'disku': 32}, 'b': [{'data1': {'value': [1513828378471L, 1]}, 'name1': 'jiekou1'}]}
32
37
0.2
100
1513828378471


输出key的列表和alue的列表

dict = {"a" : "apple", "b" : "banana", "g" : "grape", "o" : "orange"}
print dict.keys()
print dict.values()
运行结果:
['a', 'b', 'o', 'g']
['apple', 'banana', 'orange', 'grape']


调用sorted()排序
dict = {"d" : "apple", "c" : "grape", "a" : "orange", "b" : "banana"}
按照key排序
print sorted(dict.items(), key=lambda d: d[0])
运行结果:
[('a', 'orange'), ('b', 'banana'), ('c', 'grape'), ('d', 'apple')]
按照value排序
print sorted(dict.items(), key=lambda d: d[1])
运行结果:
[('d', 'apple'), ('b', 'banana'), ('c', 'grape'), ('a', 'orange')]


字典的浅拷贝

dict = {"a" : "apple", "b" : "grape"}
dict2 = {"c" : "orange", "d" : "banana"}
dict2 = dict.copy()
print dict2
运行结果:
{'a': 'apple', 'b': 'grape'}

字典的深拷贝
import copy
dict = {"a" : "apple", "b" : {"g" : "grape","o" : "orange"}}
dict2 = copy.deepcopy(dict)
dict3 = copy.copy(dict)
dict2["b"]["g"] = "orange"
print dict
dict3["b"]["g"] = "orange"
print dict
运行结果:
{'a': 'apple', 'b': {'o': 'orange', 'g': 'grape'}}
{'a': 'apple', 'b': {'o': 'orange', 'g': 'orange'}}


判断指定键值是否存在的两种方法

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import json

json = {"client":"on"}

print json.has_key("client")
print "server" in json.keys()
运行结果:
True
False


补充:字典(dict)和字符串(str)相互转换

JSON转换为字典:
dictinfo = json.loads(json_str) 输出dict类型
字典转换为JSON:
jsoninfo = json.dumps(dict) 输出str类型

实践:

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import json
from sys import argv

str = argv[1]
print str
print type(str)
dict = json.loads(str)
print dict
print type(dict)
print dict["appid"]
运行代码:python hehe.py {\"appid\":\"baidu\"\,\"description\":\"123456\"}

输出结果:

{"appid":"baidu","description":"123456"}
<type 'str'>
{u'description': u'123456', u'appid': u'baidu'}
<type 'dict'>
baidu


参考:

http://www.169it.com/article/12896573249876597531.html

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小强签名设计

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值