关于字典的一些小知识

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]

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值