【Python学习笔记】字典的管理操作

一、关于字典

  • 被定义在一对大括号{ }中的数据
  • key-value对进行存储,不同的键值对使用逗号隔开
  • 键要唯一,值可以为任意类型的数据
  • 注意:字典是可变的数据

1.字典的用法

data = {"user":"wangshengjj","password":"wsjj"}
print(type(data))
print(data)

<class 'dict'>
{'user': 'wangshengjj', 'password': 'wsjj'}
data = {"192.168.122.10":{"ssh_user":"root","ssh_port":22},
        "192.168.122.20":{"ssh_user":"root","ssh_port":22}}
print(type(data))
print(data)

<class 'dict'>
{'192.168.122.10': {'ssh_user': 'root', 'ssh_port': 22}, '192.168.122.20': {'ssh_user': 'root', 'ssh_port': 22}}

二、字典数据管理操作

1.获取数据

#使用本方法,如果键不存在于字典中,那么就会返回执行错误
data = {"user":"wangshengjj","password":"wsjj"}
print(data["user"])	#中括号里输入键,获取值

wangshengjj

data = {"user":"wangshengjj","password":"wsjj"}
print(data.get("password"))

wsjj

#在字典中取值的时候,推荐使用下面的方法,如果键不存在于字典中,下面的方法就会返回空结果
data = {"user":"wangshengjj","password":"wsjj"}
print(data.get("passwd"))

None

2.向字典添加数据

data = {"user01":"wangshengjj","password01":"wsjj"}
data["user02"] = "网笙久久"
data["password02"] = "wsjj.top"
print(data)

{'user01': 'wangshengjj', 'password01': 'wsjj', 'user02': '网笙久久', 'password02': 'wsjj.top'}

3.修改数据

可以看到,添加数据修改数据,结构是一样的
所以以后在添加数据的时候,需要注意,新增数据的不能和已有冲突

data = {"user":"wangshengjj","password":"wsjj"}
data["user"] = "网笙久久"
data["password"] = "wsjj.top"
print(data)

{'user': '网笙久久', 'password': 'wsjj.top'}

三、字典对象的操作方法

1.以列表的方式,返回字典里所有的键

data = {"user":"wangshengjj","password":"wsjj"}
print(data.keys())

dict_keys(['user', 'password'])

2.以列表的方式,返回字典里所有的值

data = {"user":"wangshengjj","password":"wsjj"}
print(data.values())

dict_values(['wangshengjj', 'wsjj'])

3.以列表的方式,返回字典里包含键值对的多个元组

data = {"user":"wangshengjj","password":"wsjj"}
print(data.items())

dict_items([('user', 'wangshengjj'), ('password', 'wsjj')])

四、遍历字典

data = {"user":"wangshengjj","password":"wsjj"}
for i in data:
    print(i)
    
user
password

data = {"user":"wangshengjj","password":"wsjj"}
for i in data:
    print("%s:%s" %(i, data.get(i)))

user:wangshengjj
password:wsjj

#上面的另外一种写法
data = {"user":"wangshengjj","password":"wsjj"}
for i,j in data.items():	#使用items
    print("%s:%s" %(i, j))
    
user:wangshengjj
password:wsjj

1.案例

data = {"192.168.122.10":{"ssh_user":"root","ssh_port":22},
        "192.168.122.20":{"ssh_user":"root","ssh_port":22}}
for a in data.items():
        print("ssh %s@%s -p %s" %(a[1]["ssh_user"],a[0],a[1]["ssh_port"]))

ssh root@192.168.122.10 -p 22
ssh root@192.168.122.20 -p 22

另外一种写法

data = {"192.168.122.10":{"ssh_user":"root","ssh_port":22},
        "192.168.122.20":{"ssh_user":"root","ssh_port":22}}
for ip, info in data.items():
        print("ssh %s@%s -p %s" % (info.get("ssh_user"),ip,info.get("ssh_port")

ssh root@192.168.122.10 -p 22
ssh root@192.168.122.20 -p 22