python中的字典Dict

Python中,字典由任意个元素构成的集合,每一个元素称为Item,也称为Entry。这个Item是由(key, value)组成的二元组。

字典是可变的、无序的、key不重复的key-value键值对集合


创建字典

dict(**kwargs)使用name=value对初始化一个字典

dict(iterable, **kwarg)使用可迭代对象和name=value对构造字典,不过可迭代对象的元素必须是一个二元结构**

dict(mapping, **kwarg)使用一个字典构建另一个字典···

d1 = {}
d1
Out[3]: {}
    
d2 = dict()
d2
Out[5]: {}
    
d3 = dict(a=100, b=200)
d3
Out[7]: {'a': 100, 'b': 200}
    
d4 = dict(d3) # 构造另外一个字典
d4
Out[9]: {'a': 100, 'b': 200}
    
d5 = dict(d4, a=300, c=400)
d5
Out[11]: {'a': 300, 'b': 200, 'c': 400}
    
d6 = dict([('a', 100), ['b', 200], (1, 'abc')], b=300, c=400)
d6
Out[13]: {'a': 100, 'b': 300, 1: 'abc', 'c': 400}

****************************************************************
    
d7=dict.fromkeys(range(5))
d7
Out[15]: {0: None, 1: None, 2: None, 3: None, 4: None}

d8=dict.fromkeys(range(5),[])
d8
Out[17]: {0: [], 1: [], 2: [], 3: [], 4: []}

元素访问

d[key]

​ 返回key对应的值value

​ key不存在抛出KeyError异常

d5
Out[20]: {'a': 300, 'b': 200, 'c': 400}

d5['a']
Out[22]: 300
    
d5['d']
Traceback (most recent call last):
  File "C:\Python\Python368\lib\site-packages\IPython\core\interactiveshell.py", line 3343, in run_code
    exec(code_obj, self.user_global_ns, self.user_ns)
  File "<ipython-input-21-d5cf6d76eae0>", line 1, in <module>
    d5['d']
KeyError: 'd'

get(key[, default])

​ 返回key对应的值value

​ key不存在返回缺省值,如果没有设置缺省值就返回None

d5.get('a')
Out[24]: 300
    
d5.get('d')

d5.get('d',123)
Out[25]: 123
    
d5
Out[26]: {'a': 300, 'b': 200, 'c': 400}

setdefault(key[, default])

​ 返回key对应的值value

​ key不存在,添加kv对,value设置为default,并返回default,如果default没有设置,缺省为None

d5
Out[26]: {'a': 300, 'b': 200, 'c': 400}
    
d5.setdefault('a')
Out[27]: 300
    
d5.setdefault('d')

d5
Out[29]: {'a': 300, 'b': 200, 'c': 400, 'd': None}
    
d5.setdefault('e',12344)
Out[30]: 12344
    
d5
Out[31]: {'a': 300, 'b': 200, 'c': 400, 'd': None, 'e': 12344}

新增和修改

d[key] = value

​ 将key对应的值修改为value

​ key不存在添加新的kv对

d5
Out[31]: {'a': 300, 'b': 200, 'c': 400, 'd': None, 'e': 12344}
d5['d']='sadas'
d5
Out[33]: {'a': 300, 'b': 200, 'c': 400, 'd': 'sadas', 'e': 12344}

update([other]) -> None

​ 使用另一个字典的kv对更新本字典

​ key不存在,就添加

​ key存在,覆盖已经存在的key对应的值

​ 就地修改

d4
Out[38]: {'a': 100, 'b': 'hahh'}
d5
Out[39]: {'a': 300, 'b': 200, 'c': 400, 'd': 'sadas', 'e': 12344}
d5.update(d5,['c',333],f=444,w=5555)
# 字典,列表不能同时存在
Traceback (most recent call last):
  File "C:\Python\Python368\lib\site-packages\IPython\core\interactiveshell.py", line 3343, in run_code
    exec(code_obj, self.user_global_ns, self.user_ns)
  File "<ipython-input-40-56ab7002473b>", line 1, in <module>
    d5.update(d5,['c',333],f=444,w=5555)
TypeError: update expected at most 1 arguments, got 2

d5.update(d4,a=4,b=5)
d5
Out[49]: 
{'a': 4,
 'b': 5,
 'c': 400,
 'd': 'sadas',
 'e': 12344,
 1: 44,
 2: 555,
 'f': 444,
 'w': 5555}

d5.update([(1,44),(2,555)],['c',333],f=444,w=5555)
# 多个列表也不行
Traceback (most recent call last):
  File "C:\Python\Python368\lib\site-packages\IPython\core\interactiveshell.py", line 3343, in run_code
    exec(code_obj, self.user_global_ns, self.user_ns)
  File "<ipython-input-41-c8888f93dfb1>", line 1, in <module>
    d5.update([(1,44),(2,555)],['c',333],f=444,w=5555)
TypeError: update expected at most 1 arguments, got 2

d5.update([(1,44),(2,555)],f=444,w=5555)
d5
Out[43]: 
{'a': 300,
 'b': 200,
 'c': 400,
 'd': 'sadas',
 'e': 12344,
 1: 44,
 2: 555,
 'f': 444,
 'w': 5555}

d5.update(d4)
d5
Out[47]: 
{'a': 100,
 'b': 'hahh',
 'c': 400,
 'd': 'sadas',
 'e': 12344,
 1: 44,
 2: 555,
 'f': 444,
 'w': 5555}

删除

pop(key[, default])

​ key存在,移除它,并返回它的value

​ key不存在,返回给定的default

​ default未设置,key不存在则抛出KeyError异常

popitem()

​ 移除并返回一个任意的键值对

​ 字典为empty,抛出KeyError异常

clear()

​ 清空字典

遍历

1、遍历Key

d5
Out[63]: {'a': 300, 'b': 'hahh', 'c': 400}
for key in d5:
    print(key)
    
a
b
c
for key in d5.keys():
    print(key)
    
a
b
c

2、遍历Value

for v in d5.values():
    print(v)
    
300
hahh
400
for key in d5.keys():
    print(d5[key])
    
300
hahh
400

3、遍历Item

d5
Out[68]: {'a': 300, 'b': 'hahh', 'c': 400}
    
    
for i in d5.items():
    print(type(i),i[0],i[1])
    
<class 'tuple'> a 300
<class 'tuple'> b hahh
<class 'tuple'> c 400

for k in d5.items():
    print(k)
    
('a', 300)
('b', 'hahh')
('c', 400)


for k,v in d5.items():
    print(k,v)
    
a 300
b hahh
c 400


for k,_ in d5.items():
    print(k)
    
a
b
c


for _,v in d5.items():
    print(v)
    print(_)
    
300
a
hahh
b
400
c

defaultdict

缺省字典

from collections import defaultdict

d = defaultdict(list)
for k in 'abcd':
    d[k].extend(range(4))
print(d)
for k,v in d.items():
    print(k,v,sep=':')

用defaultdict创建缺省字典,方便对数据的添加

添加的时候直接调用defaultdict中的函数,例如上代码的list函数

字典的长度

len(dict()) 时间复杂度为1,不用遍历

posted @ 2022-11-25 17:03  厚礼蝎  阅读(73)  评论(0编辑  收藏  举报