每天学点Python之dict

字典用来存储键值对,在Python中同一个字典中的键和值都可以有不同的类型。

字典的创建

创建一个空的字典有两种方法:

d = {}
d = dict()

而创建一个包含元素的字典方法比较多,下面操作结果相同:

>>> a = dict(one=1, two=2, three=3)
>>> b = {"one": 1, "two": 2, "three": 3}
>>> c = dict(zip(["one", "two", "three"], [1, 2, 3]))
>>> d = dict([("two", 2), ("one", 1), ("three", 3)])
>>> e = dict({"three": 3, "one": 1, "two": 2})

字典的查询

获取字典中的值只需通过dict[key]来获取,如果不存在该键,会抛出KeyError错误;也可用dict.get(k[,default])方法来获取,这个方法即使键不存在也不会抛出错误,也可以给一个默认的值,在键值对不存在时返回:

>>> a = dict(one=1, two=2, three=3)
>>> a["one"]
1
>>> a["four"]
Traceback (most recent call last):
  File "<input>", line 1, in <module>
KeyError: "four"
>>> a.get("four")

>>> a.get("four",4)
4

字典的修改

要修改字典中的键对应的值,只需要取出来直接对它赋值就行,需要注意的是,如果修改的键原来不存在,就变成了向字典中增加了一个键值对:

>>> a = dict(one=1, two=2, three=3)
>>> a["one"]=10
>>> a
{"two": 2, "one": 10, "three": 3}
>>> a["four"]=4
>>> a
{"two": 2, "four": 4, "one": 10, "three": 3}

dict.setdefault(key[,default])在key存在时,不做修改返回该值,如果不存在则添加键值对(key, default),其中default默认为None:

>>> a = dict(one=1, two=2, three=3)
>>> a.setdefault("one")
1
>>> a
{"two": 2, "one": 1, "three": 3}
>>> a.setdefault("four")
>>> a
{"two": 2, "four": None, "one": 1, "three": 3}

批量增加有dict.update(p)方法。

字典的删除

如果要删除一个键值对,直接用del方法,试图删除一个不存在的键值对会抛出KeyError错误:

>>> a
{"two": 2, "four": 4, "one": 10, "three": 3}
>>> del a["four"]
>>> a
{"two": 2, "one": 10, "three": 3}
>>> del a["four"]
Traceback (most recent call last):
  File "<input>", line 1, in <module>
KeyError: "four"

此外同样可以调用dict.clear()来清空字典。还有dict.pop(key[,default])dict.popitem(),这两个一个是弹出特定键对应的键值对,另一个弹出任意的一个键值对:

>>> a
{"two": 2, "one": 10, "three": 3}
>>> a.pop("one")
10
>>> a
{"two": 2, "three": 3}
>>> a.popitem()
("two", 2)
>>> a
{"three": 3}

字典的集合

字典可以分别返回它所有的键值对、键和值,它们的类型都是字典内置类型,可以通过list()转化为列表:

>>> a = dict(one=1, two=2, three=3)
>>> a
{"two": 2, "one": 1, "three": 3}
>>> a.items()
dict_items([("two", 2), ("one", 1), ("three", 3)])
>>> a.values()
dict_values([2, 1, 3])
>>> a.keys()
dict_keys(["two", "one", "three"])
>>> list(a.keys())
["two", "one", "three"]
文章导航