dic = {'key1' : 'value1', 'key2': 'value2' }
一、增
if
'key3'
not
in
dic
:
dic
[
'key3'
]
=
'value3'
二、删
del dic
[
'key1'
]
# 删除键是
'Name'
的条目
dic
.
clear
(
)
# 清空字典所有条目
del dic # 删除字典
三、改
dic
[
'key1'
]
=
'value0'
# 更新
四、查
- 遍历
for
key
,
value
in
dic
.
items
(
)
:
print
(
key
,
value
)
#同时遍历 key,value
for
i
in
dic
.
items
(
)
:
print
(
i
,
i
[
1
]
)
# i为列表
[
key
,
value
]
,
for
i
in
dic
:
print
(
i
,
dic
[
i
]
)
#前者为key,后者为value
for
key
in
dic
.
keys
(
)
:
print
(
key
)
#单独遍历可key
for
value
in
dic
.
values
(
)
:
print
(
value
)
#单独遍历value
五、排序
sorted函数,
sorted(iterable,key,reverse)
,sorted一共有iterable,key,reverse这三个参数
sorted
(
dic
.
keys
(
)
)
#仅根据key来排序
sorted
(
dic
.
items key
=
lamda item
:
item
[
i
]
)
#根据value排序
# 排序结果数据类型为list