每天学点Python之dict

x33g5p2x  于2021-03-13 发布在 Python  
字(2.1k)|赞(0)|评价(0)|浏览(681)

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

字典的创建

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

  1. d = {}
  2. d = dict()

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

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

字典的查询

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

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

字典的修改

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

  1. >>> a = dict(one=1, two=2, three=3)
  2. >>> a['one']=10
  3. >>> a
  4. {'two': 2, 'one': 10, 'three': 3}
  5. >>> a['four']=4
  6. >>> a
  7. {'two': 2, 'four': 4, 'one': 10, 'three': 3}

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

  1. >>> a = dict(one=1, two=2, three=3)
  2. >>> a.setdefault('one')
  3. 1
  4. >>> a
  5. {'two': 2, 'one': 1, 'three': 3}
  6. >>> a.setdefault('four')
  7. >>> a
  8. {'two': 2, 'four': None, 'one': 1, 'three': 3}

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

字典的删除

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

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

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

  1. >>> a
  2. {'two': 2, 'one': 10, 'three': 3}
  3. >>> a.pop("one")
  4. 10
  5. >>> a
  6. {'two': 2, 'three': 3}
  7. >>> a.popitem()
  8. ('two', 2)
  9. >>> a
  10. {'three': 3}

字典的集合

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

  1. >>> a = dict(one=1, two=2, three=3)
  2. >>> a
  3. {'two': 2, 'one': 1, 'three': 3}
  4. >>> a.items()
  5. dict_items([('two', 2), ('one', 1), ('three', 3)])
  6. >>> a.values()
  7. dict_values([2, 1, 3])
  8. >>> a.keys()
  9. dict_keys(['two', 'one', 'three'])
  10. >>> list(a.keys())
  11. ['two', 'one', 'three']

相关文章