字典
# 1.存储数据比较大
# 2.字典的查找速度比列表快
# 3.字典都是通过键来操作的,且键必须是唯一的。
# 4.# dic = {"键":"值","key":"value"}
字典的增删改查
字典增:
dic = {}
dic["键"]= 值 添加键值对
dic = {}
dic.setdefault("键",值) 有则更改,无则添加
字典删:
dic = {"111":[2,3,4],"222":[567]}
dic.pop("键") 通过键指定删除
dic = {"111":[2,3,4],"222":[567]}
dic.popitem() 随机删除键值对
dic = {"111":[2,3,4],"222":[567]}
del dic["111"] 指定删除键值对
dic = {"111":[2,3,4],"222":[567]}
dic.clear 删除整个字典
字典改:
dic = {"111":[2,3,4],"222":[567]}
dic[键] = 值 通过键修改值
字典查:
dic = {"111":[2,3,4],"222":[567]}
print(dic["111"]) 通过找键查询
大题示例:
要求得到的结果:{"河南":3,"河北":2,"北京":1,"内蒙":1}
id = [120121198903119561,
120121198903110561,
120121196903119561,
130482198307144762,
130482198307144662,
110121197805144347,
150121197502122799]
addrs = {
120: "河南",
130: "河北",
110: "北京",
150: "内蒙",
}
-----------------------------------------------------------------------------------------
答:
id = [120121198903119561,
120121198903110561,
120121196903119561,
130482198307144762,
130482198307144662,
110121197805144347,
150121197502122799]
addrs = {
120: "河南",
130: "河北",
110: "北京",
150: "内蒙",
dic = {} #创建一个空的字典
for i in id: 循环id这个列表
if dic.get(addrs.get(int(str(i)[0:3]))): 通过对i的切片拿到前三位做addrs的键,但是整数不支持切片需要str转换一下,切完后还要转回到整数做键,if判断dic这个字典中是否有这个值。
dic[addrs.get(int(str(i)[0:3]))] += 1 如果这个字典中有就加一
else:
dic[addrs.get(int(str(i)[0:3]))] = 1 如果这个字典没有就创建1个,默认数为1.
print(dic)
字符串转字典
dic = {}
s = "{'key1':1,'key2':2,'key3':3}"
f = open("demo","a+",encoding="utf-8")
f.write(s)
f.seek(0)
f1 = f.read()
lst = f1[1:-1].replace("'","").split(",")
for i in lst:
k,v = i.split(":")
dic[k] = v
print(dic,type(dic))
原文地址:https://www.cnblogs.com/biyunfeng/p/11934575.html
时间: 2024-10-26 12:10:46