1、字典中增加、删除、修改元素
clients = {"1.0weight":1,"1.0bias":2,"1.1weight":3,"1.0bias":4,"2.1weight":5,"2.1bias":6}
print("clients",clients)
clients["2.0weight"] = 10#增加元素
print("clients",clients)
clients["2.0weight"] = 20
print("clients",clients)#修改元素
clients.pop("2.0weight")
print("clients",clients)#删除元素
输出结果:
clients {'1.0weight': 1, '1.0bias': 4, '1.1weight': 3, '2.1weight': 5, '2.1bias': 6}
clients {'1.0weight': 1, '1.0bias': 4, '1.1weight': 3, '2.1weight': 5, '2.1bias': 6, '2.0weight': 10}
clients {'1.0weight': 1, '1.0bias': 4, '1.1weight': 3, '2.1weight': 5, '2.1bias': 6, '2.0weight': 20}
clients {'1.0weight': 1, '1.0bias': 4, '1.1weight': 3, '2.1weight': 5, '2.1bias': 6}
2、将一个字典的内容赋给另一个字典
将clients的内容赋给client中用client.update(clients)
client={"aaa":111}
clients = {"1.0weight":1,"1.0bias":2,"1.1weight":3,"1.0bias":4,"2.1weight":5,"2.1bias":6}
client.update(clients)
print("clients",clients)
print("client",client)
输出结果:
clients {'1.0weight': 1, '1.0bias': 4, '1.1weight': 3, '2.1weight': 5, '2.1bias': 6}
client {'aaa': 111, '1.0weight': 1, '1.0bias': 4, '1.1weight': 3, '2.1weight': 5, '2.1bias': 6}
3、有些时候,我们想要把键中包含某些字符的键对应的键值对输出来,可以这样实现:
例如:clients = {"1.0weight":1,"1.0bias":2,"1.1weight":3,"1.0bias":4,"2.1weight":5,"2.1bias":6}
现在我们想要把键中包含‘weight’的值重新以键值对的形式存储到另一个字典中:
client={}
clients = {"1.0weight":1,"1.0bias":2,"1.1weight":3,"1.0bias":4,"2.1weight":5,"2.1bias":6}
for i in clients.keys():
if 'weight' in i:
client[str(i)] = clients[str(i)]#将clients中包含weight的键对应的键值对取出来复制到client中
print("client:",client)
输出结果:
client: {'1.0weight': 1, '1.1weight': 3, '2.1weight': 5}
如果只想取键对应的值,则可以这样处理:
client=[]#注意,这里client是列表的形式了
clients = {"1.0weight":1,"1.0bias":2,"1.1weight":3,"1.0bias":4,"2.1weight":5,"2.1bias":6}
for i in clients.keys():
if 'weight' in i:
client.append(clients[str(i)])
print("client:",client)
输出结果:
client: [1, 3, 5]