gpt4 book ai didi

python - 更新字典值中的列表

转载 作者:太空宇宙 更新时间:2023-11-04 11:11:54 25 4
gpt4 key购买 nike

如何在列表中附加字典?

比如我有如下数据:

  [{
"data": "11_1",
"invals": [
{
"num1": "1111111",
"ifName": "Vlan1",
"pairs": {
"TYPE": "3",
"IS_TYPE": "level-2",
"IP": "192.168.1.1",
}
}
]
},
{
"data": "11_2",
"invals": [
{
"num1": "2222222",
"ifName": "Vlan2",
"pairs": {
"TYPE": "3",
"IS_TYPE": "level-2",
"IP": "192.168.1.2",
}
}
]
},
{
"data": "11_3",
"invals": [
{
"num1": "33333333",
"ifName": "Vlan3",
"pairs": {
"TYPE": "3",
"IS_TYPE": "level-2",
"IP": "192.168.1.3",
}
}
]
}]

我只想提取数据 ifNameIP。在这里我想得到:

[{'int': 'Vlan1', 'address': '192.168.1.1'},{'int': 'Vlan2', 'address': '192.168.1.3'},{'int': 'Vlan3', 'address': '192.168.1.3'}]

代码:

    out = [{ 'int': '', 'address': '' }]
for x in output:
for i in x['invals']:
if id == i['num1'] and 'IP' in i['pairs']:
if not i['pairs']['IP'] is '':
out[0]['interface'] = i['ifName']
out[0]['address'] = i['pairs']['IP']
if not i['ifName'] in out[0]['interface']:
out[0]['interface'].update(i['ifName'])
out[0]['address'].update(i['pairs']['IP'])

一直在覆盖旧的,无法更新。

最佳答案

使用以下列表理解:

[{'int': d['invals'][0]['ifName'], 'address': d['invals'][0]['pairs']['IP']} for d in l]

输出:

[{'int': 'Vlan1', 'address': '192.168.1.1'},
{'int': 'Vlan2', 'address': '192.168.1.2'},
{'int': 'Vlan3', 'address': '192.168.1.3'}]

注意:这假定您在列表的每个元素中都保持相同的结构。

关于python - 更新字典值中的列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57999877/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com