Python字典
1) 用大括号包裹,以逗号分割每个键值对,键与值之间使用冒号连接, {key:values,key:values}
2)键: 需要是不可变的数据结构, 值可以是任意的数据对象
3) 字典是无序的,键在字典中必须是唯一,在字典中取值的方式是以键寻找相对应的值
增加
(1)dict["w"] = "watermelon"
(2)
或者使用setdefault()
setdefault:两个参数,key和value,功能是给字典添加一项,如果该项已经存在,那么便不更新,如果不存在,则添加上。
dict = {}
dict.setdefault("a")
print dict
dict["a"] = "apple"
dict.setdefault("a","default")
print dict
(3)
或者使用update
update:利用一个字典a更新另外一个字典b。a字典中的key和value在b中,则覆盖,不在则添加(其实是改的功能,也有增的功能)。
dict.update({'d':'dddd'})
删除
(1)
del(dict["a"])
(2)
print dict.pop("b")
(3)随机删除一个
dict.potitem()
(4)清空所有
dict.clear()
修改
(1)
dict["g"] = "grapefruit"
(2)
dict.update({'d':'dddd'})
查询
(1)
dict.get('b')
(2)此种方法如果不存在会抛出异常
dict['b']
(3)查询所有
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
#使用列表、字典作为字典的值
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"}
#字典中元素的获取方法
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
#调用sorted()排序
dict = {"a" : "apple", "b" : "grape", "c" : "orange", "d" : "banana"}
print dict
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 update()
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'}