字典的常用操作
Posted guoqiming
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了字典的常用操作相关的知识,希望对你有一定的参考价值。
dic = {
‘name‘: ‘alex‘,
‘name‘: ‘太白金星‘,
‘age‘: 18
}
键唯一
print(dic)
数据关联性
dic = {
‘name_list‘: [‘博哥‘, ‘菊哥‘, ‘b哥‘],
‘barry‘: {
‘name‘: ‘太白金星‘,
‘age‘: 18,
‘hobby‘: ‘wife‘,
}
}
增删改查
dic = {
‘name‘: ‘太白金星‘, ‘age‘: 18,
‘hobby‘: ‘wife‘,
}
增:
1,有则修改,无则添加
dic[‘hight‘] = 176
dic[‘age‘] = 23
print(dic)
2,有责不变,无责添加
dic.setdefault(‘weight‘) # {‘name‘: ‘太白金星‘, ‘age‘: 18, ‘hobby‘: ‘wife‘, ‘weight‘: None}
dic.setdefault(‘weight‘,160) # {‘name‘: ‘太白金星‘, ‘age‘: 18, ‘hobby‘: ‘wife‘, ‘weight‘: 160}
dic.setdefault(‘name‘,‘barry‘) # {‘name‘: ‘太白金星‘, ‘age‘: 18, ‘hobby‘: ‘wife‘}
print(dic)
删:
pop 按照键删除
ret = dic.pop(‘age‘) # 按照键删除掉键值对
print(ret)
dic.pop(‘age1‘) # 没有报错
ret = dic.pop(‘age1‘, ‘没有此键‘) # 设置两个参数,第二个参数是提示语 一般设置成None
print(ret)
print(dic)
clear 清空
dic.clear()
print(dic)
popitem 3.6版本之后就是删除最后一个键值对
ret = dic.popitem()
print(ret)
print(dic)
del
del dic[‘name‘] # 按照键删除
del dic[‘name1‘]
del dic # 删除字典
print(dic)
改
dic[‘age‘] = 30
print(dic)
update
dic.update(car=‘逍客‘, money=1300)
dic = {"name": "jin", "age": 18, "sex": "male"}
dic2 = {"name": "alex", "weight": 75}
dic2.update(dic)
将dic里面的键值对覆盖添加到dic2中
print(dic) # {‘name‘: ‘jin‘, ‘age‘: 18, ‘sex‘: ‘male‘}
print(dic2) # {‘name‘: ‘jin‘, ‘weight‘: 75, ‘age‘: 18, ‘sex‘: ‘male‘}
print(dic)
查 1,不好
print(dic[‘age‘])
print(dic[‘age1‘])
2,get
print(dic.get(‘age‘))
没有此键默认返回None
print(dic.get(‘age1‘))
可以设置返回值
print(dic.get(‘age1‘, ‘没有此键‘))
dic = {
‘name‘: ‘太白金星‘,
‘age‘: 18,
‘hobby‘: ‘wife‘,
}
for i in dic:
print(i)
dic.keys() 类似于list的容器类类型
ret = dic.keys()
print(ret, type(ret))
for key in ret:
print(key)
print(ret[0])
可以转化成list
print(list(ret))
dic.values()
print(dic.values())
转化成list
print(list(dic.values()))
for v in dic.values():
print(v)
print(dic.items())
print(list(dic.items()))
for i in dic.items():
print(i)
分别赋值
a, b = (1, 2)
print(a,b)
a, b, c = (1, 2, 3)
print(a,b,c)
a, b = 100, 1000
a, b = [100, 1000]
a, b = {‘name‘:‘alex‘, ‘age‘: 73}
print(a,b)
面试题:
‘‘‘
a = 18
b = 32
通过一行代码 将a,b的值互换。
‘‘‘
a = 18
b = 32
a, b = b, a
print(a,b)
print(dic.items())
for k,v in dic.items():
‘‘‘
k,v = (‘name‘, ‘太白金星‘)
k,v = (‘age‘, 18)
k,v = (‘hobby‘, ‘wife‘)
‘‘‘
print(‘这是键:‘, k)
print(‘这是值:‘, v)
dic = {
‘name_list‘: [‘博哥‘, ‘菊哥‘, ‘b哥‘, ‘alex‘],
‘barry‘: {
‘name‘: ‘太白金星‘,
‘age‘: 18,
‘hobby‘: ‘wife‘,
}
}
1,给这个列表[‘博哥‘, ‘菊哥‘, ‘b哥‘, ‘alex‘] 追加一个元素 ‘老男孩‘。
l1 = dic[‘name_list‘]
print(l1)
l1.append(‘老男孩‘)
print(dic)
简写;
dic[‘name_list‘].append(‘老男孩‘)
print(dic)
2,将这个列表[‘博哥‘, ‘菊哥‘, ‘b哥‘, ‘alex‘]中的alex变成首字母大写。
print(dic[‘name_list‘][-1].capitalize())
dic[‘name_list‘][-1] = dic[‘name_list‘][-1].capitalize()
print(dic)
3,将这个键值对 ‘name‘: ‘太白金星‘ 的 ‘太白金星‘ 改成男神。
先通过dic 找到小字典
print(dic[‘barry‘])
在通过小字典将name 对应的值更改
dic[‘barry‘][‘name‘] = ‘男神‘
print(dic)
4,给barry对应的小字典增加一个键值对: weight: 160
dic[‘barry‘][‘weight‘] = 150
print(dic)
以上是关于字典的常用操作的主要内容,如果未能解决你的问题,请参考以下文章