Python 在数组中匹配时更新值

Python 在数组中匹配时更新值,python,json,list,dictionary,for-loop,Python,Json,List,Dictionary,For Loop,当主机名为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" }

当主机名为
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并将其写回数据?

直接分配在这里应该可以正常工作:

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

直接分配在这里应该很好:

for item in data:
    if item['hostname'] == 'c.example.com':
        item['Id'] = '10'
您可以尝试以下方法:

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循环
迭代元素,并使用
if
搜索
c.example.com
。如果使用
=
运算符匹配,则为
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'}]
您可以尝试以下方法:

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循环
迭代元素,并使用
if
搜索
c.example.com
。如果使用
=
运算符匹配,则为
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'}]

如果
项['Id']=10

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

如果
项['Id']=10

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

@比尔:它经过测试,符合你的要求。这就是你所期望的吗?@比尔:它经过测试,符合你的要求。这就是你所期待的吗?谢谢,我觉得太复杂了。谢谢,我觉得太复杂了。