在Dict值内更新列表

时间:2019-09-18 19:51:52

标签: python list dictionary

如何将字典添加到列表中?

例如,我的数据如下:

  [{
    "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'])

它已经被覆盖旧了,无法更新。

2 个答案:

答案 0 :(得分:2)

使用以下列表理解:

[{'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'}]

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

答案 1 :(得分:1)

您的代码每个循环都会覆盖out的第一个元素,因为您每次都引用out[0]。假设您尝试获取具有设置IP的唯一接口的列表,则可能要使用

result = []
saved_interfaces = []
for item in data:
  for inval in item['invals']:
    if id == i['num1'] and 'IP' in i['pairs']:
      if inval['pairs']['IP'] and inval['ifName'] not in saved_interfaces:
        result.append({'int':inval['ifName'],'address':inval['pairs']['IP']})
        saved_interfaces.append(inval['ifName'])
#print(result)
#[{'int': 'Vlan1', 'address': '192.168.1.1'}, {'int': 'Vlan2', 'address': '192.168.1.2'}, {'int': 'Vlan3', 'address': '192.168.1.3'}]

''被评估为False