如果说列表是支持位置读取对象的引用数组,那么字典就是支持键读取无序对象的引用表。从本质上讲,字典是作为哈希表(支持快速检索的数据结构)来实现的。一开始很小,并根据要求而增长。此外,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