在数组中匹配时更新值 [英] Update a value when matched in array

查看:64
本文介绍了在数组中匹配时更新值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在主机名是c.example.com

样本数据:

[
  {
    "hostname": "a.example.com",
    "Id": "1"
  },
  {
    "hostname": "b.example.com",
    "Id": "2"
  },
  {
    "hostname": "c.example.com",
    "Id": "1"
  },
  {
    "hostname": "d.example.com",
    "Id": "1"
  }
]

我可以匹配该物品

data=[{"hostname":"a.example.com","Id":"1"},{"hostname":"b.example.com","Id":"2"},{"hostname":"c.example.com","Id":"1"},{"hostname":"d.example.com","Id":"1"}]
for item in data:
    if item['hostname'] == 'c.example.com':
          # how to update its id to 10 and write it back to data

如何将其ID更新为10并将其写回数据?

How to update its id to 10 and write it back to data?

推荐答案

您可以尝试以下方法:

sample_data = [
{
"hostname": "a.example.com",
"Id": "1"
},
{
"hostname": "b.example.com",
"Id": "2"
},
{
"hostname": "c.example.com",
"Id": "1"
 },
{
"hostname": "d.example.com",
"Id": "1"
}
]

for item in sample_data:
    if item['hostname'] == "c.example.com":
        item['Id'] = 10

print(sample_data)

说明:

使用for-loop遍历元素,然后使用if搜索c.example.com.如果使用=运算符匹配,则将新值分配给Id

Using for-loop iterate over the elements and using if search for c.example.com. If it matches using = operator assign a new value to Id

输出:

[{'hostname': 'a.example.com', 'Id': '1'}, {'hostname': 'b.example.com', 'Id': '2'}, {'hostname': 'c.example.com', 'Id': 10}, {'hostname': 'd.example.com', 'Id': '1'}]

这篇关于在数组中匹配时更新值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆