Python之字典方法
1. 字典由键值对组成,且字典是无序的,可以进行嵌套 - dict,字典的value可以是任意类型
dict1 = {
"k1": 'test',
"k2": 1234,
"k3": None,
"k4": True,
"k5": [1,2,3],
"k6": {"a": 6,"b": "boc"},
"k7": (1,2,3)
}
2. 字典的key,不能是列表(list是动态的 ),不能是字典
dict2 = {
1: 'a',
"b": 'c',
# (1,2): None,
[3,4]: True,
{'d': 3,"e": "f"}: 3
}
当key为列表/字典时:
Traceback (most recent call last):
File "D:/Project/pythonProject/pythonProject/Mytest3/test_a.py", line 19, in <module>
dict2 = {
TypeError: unhashable type: 'list'
3. 通过key获取value,并通过索引获取到想要的值 -- * 不能通过切片方式查找(字典是无序的!)
dict3 = {
"k1": 'test',
"k2": 1234,
"k3": None,
"k4": True,
"k5": [1,2,3],
"k6": {"a": 6,"b": "boc","c": [1,2,3]},
"k7": (1,2,3)
}
print(dict1["k6"]["c"][2])
结果:3
4. 使用del ,删除某个值 - 支持删除
dict4 = {
"k1": 'test',
"k2": 1234,
"k3": None,
"k4": True,
"k5": [1,2,3],
"k6": {"a": 6,"b": "boc","c": [1,2,3]},
"k7": (1,2,3)
}
del dict4["k3"]
print(dict4)
结果:
{
'k1': 'test',
'k2': 1234,
'k4': True,
'k5': [1, 2, 3],
'k6': {
'a': 6,
'b': 'boc',
'c': [1, 2, 3]
},
'k7': (1, 2, 3)
}
5. 支持for循环,分别获取key和value
dict5 = {
"k1": 'test',
"k2": 1234,
"k3": None,
"k4": True,
"k5": [1,2,3],
"k6": {"a": 6,"b": "boc","c": [1,2,3]},
"k7": (1,2,3)
}
for item in dict5:
print(item)
结果:输出的是字典的key - 默认
for item in dict5.values:
print(item)
结果:输出为字典的value
for key,value in dict5.items():
print(key)
print(value)
结果:分别输出地点的key和value
6. fromkeys(*args, **kwargs) - 根据序列,创建字典,并指定统一的值
dict5 = {
"k1": 'test',
"k2": 1234,
"k3": None,
"k4": True,
"k5": [1,2,3],
"k6": {"a": 6,"b": "boc","c": [1,2,3]},
"k7": (1,2,3)
}
print(dict5.fromkeys([1,"test",3],'t'))
结果:{1: 't', 'test': 't', 3: 't'}
7. get(), 根据key获取值,如果传入的key存在,则返回key的value;如果key不存在,则返回设置的值:111,或者未设置值则返回None
dict5 = {
"k1": 'test',
"k2": 1234,
"k3": None,
"k4": True,
"k5": [1,2,3],
"k6": {"a": 6,"b": "boc","c": [1,2,3]},
"k7": (1,2,3)
}
v1 = dict5.get('k5',111)
print(v2)
结果:[1,2,3]
8. items,获取字典的key和value,keys()和values() 可以分别获取字典的key和value
for key,value in dict5.items(): print(key) print(value) 结果:分别输出字典的key和value
9. pop() - 传入需要删除的key,如果传入的key存在,则返回对应的key的value,如果不存在则返回设置的值9
dict6 = {
"k1": 'test',
"k2": 1234,
"k3": [1,2,'a']
}
v = dict6.pop('k3', 9)
print(v)
print(dict6) - 得到需要删除的key的value
结果:
[1, 2, 'a']
{'k1': 'test', 'k2': 1234}
10. popitem() 随机删除一个键值对
dict6 = {
"k1": 'test',
"k2": 1234,
"k3": [1,2,'a']
}
k,v = dict6.popitem()
print(k,v)
print(dict6)
结果:
k3 [1, 2, 'a']
{'k1': 'test', 'k2': 1234}
11. setdefault() 传入的key存在:获取传入key的value;若传入的key不存在,则可以设置对应的value
dict6 = {
"k1": 'test',
"k2": 1234,
"k3": [1,2,'a']
}
v = dict6.setdefault('k111','test')
print(v,dict6)
结果:test {'k1': 'test', 'k2': 1234, 'k3': [1, 2, 'a'], 'k111': 'test'}
12. update() 更新字典add
dict6 = {
"k1": 'test',
"k2": 1234,
"k3": [1,2,'a']
}
dict6.update({"k4": 123,"test":[1,2,'d']})
print(dict6)
结果:{'k1': 'test', 'k2': 1234, 'k3': [1, 2, 'a'], 'k4': 123, 'test': [1, 2, 'd']}

浙公网安备 33010602011771号