打赏

python字典

python 字典

1.定义

定义在大括号中的一组数据,以key-value键值对进行数据存储。

dict_a = {"name":"jone","password":"redme"}
print(type(dict_a))

dict_b = {"192.168.1.1":[80,22,3306],"192.168.1.2":[1001,1002]}
print(dict_b)

dict_c = {
  "192.168.1.1":{
    "ssh_user":"root",
    "ssh_port":22,
    "ssh_password":"redme"
  }
}
print(type(dict_c))

2.字典的常规操作

(1.)获取数据

dict_a = {"name":"jone","password":"redme"}
print(dict_a["name"])
print(dict_a.get("name"))

(2.)添加数据

dict_a = {"name":"jone","password":"redme"}
dict_a["email"] = "xxx.com"
print(dict_a)

(3.) 修改数据

dict_a = {"name":"jone","password":"redme"}
dict_a["passwod"]="xxx.com"
print(dict_a)

(4.) 删除数据

dict_a = {"name":"jone","password":"redme"}
del dict_a["password"]
print(dict_a)

3.字典对象的操作方法

(1.)keys() 以列表的形式返回字典中所有的键

dict_a = {"name":"jone","password":"redme","level":30}
print(dict_a.keys())

(2.) values() 以列表的形式返回字典中的所有值

dict_a = {"name":"shell","password":"redme","level":30}
print(dict_a.values())

(3.) items() 以列表的形式返回包含多个键值对组合的元组

dict_a = {"name":"shell","password":"redme","level":30}
print(dict_a.items())

(4.) 通过for循环遍历字典

# 通过dict_a.get() 获取值
dict_a = {"name":"shell","password":"redme","level":30}
for i in dict_a:
   print("key:%s,value:%s" %(i,dict_a.get(i)))
   
# 通过dict_a.items()
for k,v in dict_a.items():
    print("key:%s,value:%s" %(k,v))

案例

统计IP地址出现的次数

# ip_number字典,key为IP,value为出现的次数
ip_number = {}
ip_list = ["192.168.1.1","192.168.1.2","192.168.1.3","192.168.1.3","192.168.1.1"]

for ip in ip_list:
  if ip not in ip_number.keys()
     ip_number[ip] = 1
  else:
     ip_nmber[ip] = ip_number[ip] + 1
for k,v in ip_number.items():
   print("ip:%s,次数:%s" % (k,v))
posted @ 2021-11-13 11:02  苍山落暮  阅读(41)  评论(0编辑  收藏  举报