Python基础之字典

字典dict

字典是Python中唯一的映射类型,采用键值对(key-value)的形式存储数据。Python对key进行哈希运算,根据计算的结果决定value的存储地址,所以字典是无序存储的,且key必须是可哈希的。可哈希表示key必须是不可变类型的,如:数字、字符串、元组。
字典是Python中除列表外,最灵活的内置数据结构类型。列表是有序的对象结合,字典是无序的对象集合。两者之间的区别在于:字典当中的元素是通过键来存取的,而不是通过偏移存取。

1. 增加

```Python dic = {} dic["lst"] = ["a", "b", "c"] print(dic)

setdefault在字典中添加键值对,如果只有键,那对应的值是none

但是如果原字典中存在设置的键值对,则它不会更改或覆盖

dic.setdefault("k", "v")
print(dic)
dic.setdefault("k", "v1")
print(dic)

执行结果为:
```Python
{'lst': ['a', 'b', 'c']}
{'lst': ['a', 'b', 'c'], 'k': 'v'}
{'lst': ['a', 'b', 'c'], 'k': 'v'}

2. 删除

2.1 使用pop()删除指定值

下面是在python中的pop()源码描述。 ```Python def pop(self, k, d=None): # real signature unknown; restored from __doc__ """ D.pop(k[,d]) -> v, remove specified key and return the corresponding value. If key is not found, d is returned if given, otherwise KeyError is raised """ pass ``` pop()方法用于删除一个指定的键值对,然后返回要删除的key所对应的value值
pop()方法中有两个参数,一个是k, 一个是d。k是指要删除的值, d是当要删除的k不存在时,pop()的方法值。d在调用pop()方法时,是可以不写的,默认为None。但是,在d不写的情况下,如果没有找到特定的k值,那么就会产生KeyError错误。
下面分三种情况分别讨论pop()的结果。

2.1.1 删除存在的key值

```Python dic = {"a": 1, "b": 2} ret = dic.pop("b") print(ret) ``` 执行结果为: ```Python 2 #当删除的key存在时,那么pop()会返回一个值,就是key所对应的value值 ```

2.1.2 删除不存在的key值

在删除不存在的key值时,分两种情况讨论,一种是有设置返回值,一个是没有设置返回值,这两种的结果是不一样的。
(1)设置返回值
当删除有不存在的key时,如果有在pop()中设置返回值,那么结果是返回设置的返回值。如下面代码所示: ```Python dic = {"a": 1, "b": 2} ret = dic.pop("c", "key is not found!") print(ret) ``` 执行结果为: ```Python key is not found! ``` 如代码所示,程序的返回值和设置的pop()返回值一致。
(2)没有设置返回值
当删除有不存在的key时,如果没有在pop()中设置返回值,那么就会产生KeyError错误。如下面代码所示: ```Python dic = {"a": 1, "b": 2} ret = dic.pop("c") print(ret) ``` 执行结果为: ```Python Traceback (most recent call last): File "E:/python_workplace/test.py", line 67, in ret = dic.pop("c") KeyError: 'c'
<h3>2.2 使用popitem()删除随机值</h3>
下面是python中的popitem()源码描述。
```Python 
    def popitem(self): # real signature unknown; restored from __doc__
        """
        D.popitem() -> (k, v), remove and return some (key, value) pair as a
        2-tuple; but raise KeyError if D is empty.
        """
        pass

popitem()方法会随机的删除dict中的某组键值对,然后将删除的键值对以含有key和value两个值的元组返回, 如果dict是一个空值,那么会产生keyError错误。

2.2.1 使用popitem()删除随机值

```Python dic = {"a": 1, "b": 2} ret = dic.popitem() print(ret) print(dic) ``` 执行结果为: ```Python ('b', 2) {'a': 1} ``` 可以从结果中看出,随机删除的是key="b"的键值对。

2.2.2 使用popitem()随机删除一个空字典

```Python dic = {} ret = dic.popitem() print(ret) ``` 执行结果为: ```Python Traceback (most recent call last): File "E:/python_workplace/month08/2018-8-26/test.py", line 77, in ret = dic.popitem() KeyError: 'popitem(): dictionary is empty' ``` 报错显示:字典是空的。

2.3 使用clear()清空dict

下面是python中的clear()源码描述。 ```Python def clear(self): # real signature unknown; restored from __doc__ """ L.clear() -> None -- remove all items from L """ pass ``` clear()的作用是移除dict中的所有元素,返回值为None。 ```Python dic = {"a": 1, "b": 2} ret = dic.clear() print(ret) print(dic) ```
None    #dict.clear()返回值为None.
{}      #当dict使用clear()方法之后,那么就会清空字典中的所有元素

2.4 使用del删除dict

使用del删除dict,就是将dict对象彻底的从程序中删除。 ```Python dic = {"a": 1, "b": 2} del dic print(dic) ``` 执行结果为: ```Python Traceback (most recent call last): File "E:/python_workplace/test.py", line 87, in print(dic) NameError: name 'dic' is not defined ``` 结果显示字典对象dic没有找到,说明被del彻底的从程序中删除。

3 修改

使用dict中的update()方法,可以修改字典中的内容。 update是dict在python中的一个内置函数,源码如下所示: ```Python def update(self, E=None, **F): # known special case of dict.update """ D.update([E, ]**F) -> None. Update D from dict/iterable E and F. If E is present and has a .keys() method, then does: for k in E: D[k] = E[k] If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v In either case, this is followed by: for k in F: D[k] = F[k] """ pass ``` dic.update(dict1)中的参数dict1是一个字典,作用是将dic1中的内容更新到dic中,此时有两种情况:
(1)dic中存在和dic1中相同的key值,此时dic中key所对应的value将会被dic1中key对应的value替换
(2)dic中存在和dic1中不同的key值,此时将在dic中新增键值对,就是dic1中有,而dic中没有的
此方法没有返回值 下面将分别进行测验:

3.1 具有相同key值

```Python dic = {"a": 1, "b": 2} ret = dic.update({"a": 2}) print(dic) ``` 执行结果为: ```Python {'a': 2, 'b': 2} ``` 可以看到dic中key=a所对应的value值已经被修改

3.2 存在不同的key值

```Python dic = {"a": 1, "b": 2} dic.update({"c": 3}) print(dic) ``` 执行结果为: ```Python {'a': 1, 'b': 2, 'c': 3} ``` 可以看到dic中,新增了一个键值对,对应着就是update()中的字典。

4. 查询

4.1 通过key查询

可以直接通过dic[key]来取。
4.1.1 key在dict中
如果dic中存在key,则返回key对应的value值。 ```Python dic = {"a": 1, "b": 2} print(dic["a"]) ``` 执行结果为: ```Python 1 ```
4.1.2 key不在dict中
如果dic中存在对应的value值,则返回KeyError错误。 ```Python dic = {"a": 1, "b": 2} print(dic["c"]) ``` 执行结果为: ```Python Traceback (most recent call last): File "E:/python_workplace/test.py", line 99, in print(dic["c"]) KeyError: 'c' ```

4.2 通过get()取值

dict中有一个get()方法,可以用来获取字典中的key对应的value值。
get()在python中对应的源码如下: ```Python def get(self, k, d=None): # real signature unknown; restored from __doc__ """ D.get(k[,d]) -> D[k] if k in D, else d. d defaults to None. """ pass ``` get方法中需要两个参数,k和d。k是指要查询的字典键值,d是返回值。

4.3 其他操作

4.3.1 items()
```Python dic = {"a": 1, "b": 2} dic = {"a": 1, "b": 2} item = dic.items() print(item, type(item)) ``` 执行结果为: ```Python dict_items([('a', 1), ('b', 2)]) ``` 这个类型就是dict_items类型,可迭代的。
4.3.2 keys()
```Python dic = {"a": 1, "b": 2} keys = dic.keys() print(keys, type(keys)) ``` 执行结果为: ```Python dict_keys(['a', 'b']) ```
4.3.3 values()
```Python dic = {"a": 1, "b": 2} values = dic.values() print(values, type(values)) ``` 执行结果为: ```Python dict_values([1, 2]) ```

5. 字典的循环

5.1 循环字典

```Python dic = { "name": "yang", "age": 18, "sex": "male" } for key in dic: print(key) ``` 执行结果为: ```Python name age sex ```

5.2 循环key, value

```Python dic = { "name": "yang", "age": 18, "sex": "male" } for key, value in dic.items(): print(key, value) ``` 执行结果为: ```Python name yang age 18 sex male ```

5.3 循环value

```Python dic = { "name": "yang", "age": 18, "sex": "male" } for item in dic.items(): print(item) ``` 执行结果为: ```Python ('name', 'yang') ('age', 18) ('sex', 'male') ```
原文地址:https://www.cnblogs.com/yang-wei/p/9630484.html