-
关键字:dictionary、字典
-
摘要:dictionary、字典、字典的使用方法、字典的操作
目录
一、字典概述
1、字典
- 字典是由 键—值 对构成的数据集。
- 字典中的键只能使用字符串、数字或元组;字典的值可以是任意 Python 对象。
- 字典为散列类型,其中的 键—值 对无序且不重复。
2、字典的定义
##直接定义
>>> dict1 = {1:"one", 2:"two", 3:"three"}
##使用 dict() 函数构造
>>> dict2 = dict(dict1) # 使用字典构造
>>> dict3 = dict(name='Tom', age=18) # 使用关键字构造
>>> dict4 = dict([('1', 'one'), ('2', 'two'),('3', 'three')]) # 使用列表构造
>>> dict5 = dict((('1', 'one'), ('2', 'two'),('3', 'three'))) # 使用元组构造
*在使用关键字构造时,key不能为数字或带有数字的字符串,否则会引起歧义报错
3、向字典中添加键值对
*若该key已存在,则会覆盖原键值对
>>> dict1 = {1:"one", 2:"two", 3:"three"}
>>> dict1[4] = 'four'
>>> dict1
{1: 'one', 2: 'two', 3: 'three', 4: 'four'}
4、通过key索引对应值
*若key不存在则会报错
>>> dict1 = {1:"one", 2:"two", 3:"three"}
>>> dict1[2]
'two'
5、通过get索引对应值
*若key不存在在返回None
>>> dict1 = {1:"one", 2:"two", 3:"three"}
>>> dict1.get(1)
'one'
>>> print(dict1.get(5))
None
二、字典常用方法
1、dict1.copy浅复制
浅复制会创建新列表,但只能用于一维字典
>>> dict1 = {1:"one", 2:"two", 3:"three"}
>>> dict2 = dict1.copy()
2、setdefault 查找或添加
通过dict1.setdefault(key, value) 查找字典中的对象
-
若存在此对象,则返回其值;
- 若不存在此对象,则添加此 键—值 对。
>>> dict1 = {1:"one", 2:"two", 3:"three"}
>>> dict1.setdefault(1)
'one'
>>> dict1.setdefault(2, 'two')
'two'
>>> dict1.setdefault(4, 'four')
'four'
>>> dict1
{1: 'one', 2: 'two', 3: 'three', 4: 'four'}
3、update 使用字典更新另一字典
dict2.update(dict1) 用一个字典更新另一个字典
>>> dict1 = {1:"one", 2:"two", 3:"three"}
>>> dict2 = {1:"ONE", 4:"four"}
>>> dict1.update(dict2)
>>> dict1
{1: 'ONE', 2: 'two', 3: 'three', 4: 'four'}
4、pop 删除指定键值对并返回其值
dict1.pop(key) 删除dict1中key对应的键值对并返回该键值对的值
>>> dict1
{1: 'ONE', 2: 'two', 3: 'three', 4: 'four'}
>>> dict1.pop(1)
'ONE'
>>> dict1
{2: 'two', 3: 'three', 4: 'four'}
*popitem 随机删除一个键值对并返回该键值对
>>> dict1 = {1:"one", 2:"two", 3:"three"}
>>> dict1.popitem()
(3, 'three')
>>> dict1
{1: 'one', 2: 'two'}
5、clear 清空字典
dict1.clear() 清空字典
>>> dict1 = {1:"one", 2:"two", 3:"three"}
>>> dict1.clear()
6、items 取出所有键值对
>>> dict1 = {1:"one", 2:"two", 3:"three"}
>>> dict1.values()
dict_values(['one', 'two', 'three'])
>>> dict1.items()
dict_items([(1, 'one'), (2, 'two'), (3, 'three')])
>>> type(dict1.items())
<class 'dict_items'>
>>> list(dict1.items())
[(1, 'one'), (2, 'two'), (3, 'three')]
*keys 取出所有key
>>> dict1 = {1:"one", 2:"two", 3:"three"}
>>> dict1.keys()
dict_keys([1, 2, 3])
*values 取出所有value
>>> dict1 = {1:"one", 2:"two", 3:"three"}
>>> dict1.values()
dict_values(['one', 'two', 'three'])
三、字典遍历
用for循环结合 items 操作遍历字典
>>> dict1 = {1:"one", 2:"two", 3:"three"}
>>> for key,value in dict1:
print(str(key) + ": " + value)
>>> for key,value in dict1.items():
print(str(key) + ": " + value)
1: one
2: two
3: three