Python中dict详解
python3.0以上,print函数应为print(),不存在dict.iteritems()这个函数。
在python中写中文注释会报错,这时只要在头部加上# coding=gbk即可
#字典的添加、删除、修改操作
dict = {"a" : "apple", "b" : "banana", "g" : "grape", "o" : "orange"}
dict["w"] = "watermelon"
del(dict["a"])
dict["g"] = "grapefruit"
print dict.pop("b")
print dict
dict.clear()
print dict
#字典的遍历
dict = {"a" : "apple", "b" : "banana", "g" : "grape", "o" : "orange"}
for k in dict:
print "dict[%s] =" % k,dict[k]
#字典items()的使用
dict = {"a" : "apple", "b" : "banana", "c" : "grape", "d" : "orange"}
#每个元素是一个key和value组成的元组,以列表的方式输出
print dict.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", "c" : "grape", "d" : "orange"}
print dict.iteritems()
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",), "bo" : {"b" : "banana", "o" : "orange"}, "g" : ["grape","grapefruit"]}
print dict["a"]
print dict["a"][0]
print dict["bo"]
print dict["bo"]["o"]
print dict["g"]
print dict["g"][1]
dict = {"a" : "apple", "b" : "banana", "c" : "grape", "d" : "orange"}
#输出key的列表
print dict.keys()
#输出value的列表
print dict.values()
#每个元素是一个key和value组成的元组,以列表的方式输出
print dict.items()
dict = {"a" : "apple", "b" : "banana", "c" : "grape", "d" : "orange"}
it = dict.iteritems()
print it
#字典中元素的获取方法
dict = {"a" : "apple", "b" : "banana", "c" : "grape", "d" : "orange"}
print dict
print dict.get("c", "apple")
print dict.get("e", "apple")
#get()的等价语句
D = {"key1" : "value1", "key2" : "value2"}
if "key1" in D:
print D["key1"]
else:
print "None"
#字典的更新
dict = {"a" : "apple", "b" : "banana"}
print dict
dict2 = {"c" : "grape", "d" : "orange"}
dict.update(dict2)
print dict
#udpate()的等价语句
D = {"key1" : "value1", "key2" : "value2"}
E = {"key3" : "value3", "key4" : "value4"}
for k in E:
D[k] = E[k]
print D
#字典E中含有字典D中的key
D = {"key1" : "value1", "key2" : "value2"}
E = {"key2" : "value3", "key4" : "value4"}
for k in E:
D[k] = E[k]
print D
#设置默认值
dict = {}
dict.setdefault("a")
print dict
dict["a"] = "apple"
dict.setdefault("a","default")
print dict
#调用sorted()排序
dict = {"a" : "apple", "b" : "grape", "c" : "orange", "d" : "banana"}
print dict
#按照key排序
print sorted(dict.items(), key=lambda d: d[0])
#按照value排序
print sorted(dict.items(), key=lambda d: d[1])
#字典的浅拷贝
dict = {"a" : "apple", "b" : "grape"}
dict2 = {"c" : "orange", "d" : "banana"}
dict2 = dict.copy()
print dict2
#字典的深拷贝
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
补充:
1 初始化
>>> d = dict(name='visaya', age=20)
>>> d = dict(zip(['name', 'age'], ['visaya', 20]))
#dict.fromkeys(listkeys, default=0) 把listkeys中的元素作为key均赋值为value,默认为0
>>> d = dict.fromkeys(['a', 'b'], 1)
>>> d
{'a': 1, 'b': 1}
2 字典视图和几何
dict.keys()类似信使可以进行交集和并集等集合操作(类似集合,因为不存在重复的项),但dict.values()不可以进行如上操作。
>>> k = d.keys()
>>> k
dict_keys(['a', 'b'])
>>> list(k)
['a', 'b']
>>> k | {'x': 3}
{'a', 'x', 'b'}
>>> k | {'x'}
{'a', 'x', 'b'}
>>> k | {'x', 'y'}
{'a', 'y', 'b', 'x'}
>>> k & {'x'}
set()
>>> v = d.values()
>>> v
dict_values([1, 2])
>>> v | {'x'}
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for |: 'dict_values' and 'set'
3 排序字典键
两种方法:
3.1 sort:
>>> Ks = list(d.keys())
>>> Ks.sort()
>>> for k in Ks:
... print(k, d[k])
...
a 1
b 2
3.2 sorted:
>>> for k in sorted(d.keys()):
... print(k, d[k])
...
a 1
b 2
3.3 注意
>>> for k in list(d.keys()).sort():
... print(k, d[k])
...
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'NoneType' object is not iterable
出错原因:
list.sort() list.append()函数都是对自身的操作,没有返回值,故需先将list(d.keys())的结果保存下来,在结果上进行sort()
4 常用函数
4.1 get()
D.get(k[, d]) => D[k] if k in D else d. d defaults to none.
4.2 pop()
D.pop(value[, d]) => Remove specified key and return the
corresponding value. If key is not found, d is returned if given,
otherwise KeyError is raised.
4.3 udpate()
D.update(E, **F) -> None. Update D from dict/iterable E and F.
If E has a .keys() method, does: for k in E: D[k] = E[k]
If E lacks .keys() method, does: for (k, v) in E: D[k] = v
In either case, this is followed by: for k in F: D[k] = F[k]
>>> d = dict(name='visaya', age=21)
>>> d1= {'age': 20, 'sex': 'male'}
>>> d2 = zip(['a', 'b'], [1, 2])
>>> d.update(d1)
>>> d
{'age': 20, 'name': 'visaya', 'sex': 'male'}
#for k in d1: d[k] = d1[k]
>>> d.update(d2)
>>> d
{'age': 20, 'name': 'visaya', 'sex': 'male'}
#for (k, v) in d2: d[k] = v
4.4 del()
del D[key]
4.5 clear()
4.6 copy()
Python中的dict
初始化
构造方法创建
Python代码
d = dict()
d = dict(name="nico", age=23)
d = dict((['name', "nico"], ['age', 23]))
当然还有更方便,简单的
Python代码
d = {}
d = {"name":"nico", "age":23}
遍历
通过对key的遍历,遍历整个dict
Python代码
d = {"name":"nico", "age":23}
for key in d:
print "key=%s, value=%s" % (key, d[key])
for key in d.iterkeys():
print "key=%s, value=%s" % (key, d[key])
for key in d.keys():
print "key=%s, value=%s" % (key, d[key])
for key in iter(d):
print "key=%s, value=%s" % (key, d[key])
for key,item in d.items():
print "key=%s, value=%s" % (key, item)
当然也可以直接遍历value
Python代码
d = {"name":"nico", "age":23}
for value in d.values():
print value
for key,value in d.viewitems():
print "key=%s, value=%s" % (key, value)
for value in d.viewvalues():
print "value=%s" % (value)
这里values和viewvalues的区别
后者返回的是该字典的一个view对象,类似数据库中的view,当dict改变时,该view对象也跟着改变
常用方法
Python代码
d = {"name":"nico", "age":23}
d["name"] = "aaaa"
d["address"] = "abcdefg...."
print d #{'age': 23, 'name': 'aaaa', 'address': 'abcdefg....'}
获取dict值
Python代码
print d["name"] #nico
print d.get("name") #nico
如果key不在dict中,返回default,没有为None
Python代码
print d.get("namex", "aaa") #aaa
print d.get("namex") #None
排序sorted()
Python代码
d = {"name":"nico", "age":23}
for key in sorted(d):
print "key=%s, value=%s" % (key, d[key])
#key=age, value=23
#key=name, value=nico
删除del
Python代码
d = {"name":"nico", "age":23}
Python代码
del d["name"]
#如果key不在dict中,抛出KeyError
del d["names"]
Python代码
Traceback (most recent call last):
File "F:\workspace\project\pydev\src\ddd\ddddd.py", line 64, in <module>
del d["names"]
KeyError: 'names'
清空clear()
Python代码
d = {"name":"nico", "age":23}
d.clear()
print d #{}
copy()
Python代码
d1 = d.copy() #{'age': 23, 'name': 'nico'}
#使用返回view对象
d2 = d1.viewitems() #dict_items([('age', 23), ('name', 'nico')])
#修改字典d1,新增元素
d1["cc"] = "aaaaaa"
print d2
#dict_items([('cc', 'aaaaaa'), ('age', 23), ('name', 'nico')])
pop(key[, default])
如果key在dict中,返回,不在返回default
Python代码
#如果key在dict中,返回,不在返回default
print d.pop("name", "niccco") #nico
print d.pop("namezzz", "niccco") #niccco
#key不在dict中,且default值也没有,抛出KeyError
print d.pop("namezzz") #此处抛出KeyError
popitem()
删除并返回dict中任意的一个(key,value)队,如果字典为空会抛出KeyError
Python代码
d = {"name":"nico", "age":23}
print d.popitem() #('age', 23)
print d.popitem() #('name', 'nico')
#此时字典d已为空
print d.popitem() #此处会抛出KeyError
update([other])
将字典other中的元素加到dict中,key重复时将用other中的值覆盖
Python代码
d = {"name":"nico", "age":23}
d2 = {"name":"jack", "abcd":123}
d.update(d2)
print d #{'abcd': 123, 'age': 23, 'name': 'jack'}
原文出处:http://blog.csdn.net/tianmo2010/article/details/7621424
posted on 2012-09-17 10:31 yangyzh 阅读(249919) 评论(1) 编辑 收藏 举报