造字典

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# 造字典
# 方法一
d = {'key1':111, 'key2':222, 'key3':333}
print(d)

# 方法二
d = dict(x=1, y=2, z=3)
print(d)

# 方法三
# 复杂版
inof = [['bage', 19], ['bage1', 20],['bage2', 21]]
d={}
for item in inof:
d[item[0]] = item[1]
print(d)
# 简单版
res = dict(inof)
print(res)

# 方法四
# 复杂版
key = ['bage', 'bage1', 'bage3']
d = {}
for k in key:
d[k] = None
print(d)
#简单版
d = {}.fromkeys(key, None)
print(d)

字典可存可取

1
2
3
4
5
6
7
8
# 字典可存可取
d = {'key1':1111,'key2':2222,'key3':3333}
# 可以改value值
d['key1'] = 9999
print(d) # {'key1': 9999, 'key2': 2222, 'key3': 3333}
# 可以添加
d['key4'] = 4444
print(d) # {'key1': 9999, 'key2': 2222, 'key3': 3333, 'key4': 4444}

删除

1
2
3
4
5
6
7
8
9
10
11
12
d = {'key1':1111,'key2':2222,'key3':3333}
# del 删除key和相对应value值,没有返回值
del d['key1']
print(d) # {'key2': 2222, 'key3': 3333}
# pop 删除key和相对应value值,返回值是删除的value值
res = d.pop('key3')
print(d) # {'key2': 2222}
print(res) # 3333
# popitem 随机删除,返回值是删除的key和相对应的value值
res = d.popitem()
print(d) # {}
print(res) # ('key2', 2222)

长度len

1
2
d = {'key1':1111,'key2':2222,'key3':3333}
print(len(d)) # 3

in

1
2
3
4
# in 查的是key值
d = {'key1':1111,'key2':2222,'key3':3333}
print('key1' in d) # True
print(1111 in d) # False

值keys 值values 以及items

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# for循环
d = {'key1':1111,'key2':2222,'key3':3333}
for k in d: # 默认取key值
print(k) # key 1key2 key3
for k in d.keys(): # 取key值
print(k) # key 1key2 key3
for v in d.values(): # 取key值
print(v) # key 1key2 key3
for i in d.items(): # 取key和value值
print(i) # ('key1', 1111) ('key2', 2222) ('key3', 3333)
for k,v in d.items(): # 取key值
print(k,v) # key1 1111 key2 2222 key3 3333

print(list(d.keys())) # ['key1', 'key2', 'key3']
print(list(d.values())) # [1111, 2222, 3333]
print(list(d.items())) # [('key1', 1111), ('key2', 2222), ('key3', 3333)]

setdefault

1
2
3
4
5
6
7
8
9
10
d = {'name': 'bage'}
if 'age' in d:
...
else:
d['age'] = 19
print(d) # {'name': 'bage', 'age': 19}
# setdefault 有不加,没有就加 返回key对应的value
d = {'name': 'bage'}
d.setdefault('age', 19)
print(d) # {'name': 'bage', 'age': 19}

update

1
2
3
4
5
# 更新,没有添加,有就以新列表为准
d = {'key1':1111,'key2':2222,'key3':3333}
d.update({'key3': 9999, 'key4': 4444})
print(d) # {'key1': 1111, 'key2': 2222, 'key3': 9999, 'key4': 4444}

clear

1
2
3
4
# 清空
d = {'key1':1111,'key2':2222,'key3':3333}
d.clear()
print(d) # {}