简体   繁体   中英

Update List within Dict values

How do I append the dict within the list?

For example, I have data as follows:

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

I would like to pull only data ifName and IP . Here I would like to get:

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

CODE:

    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'])

It's been overwriting old, not able to update it.

Use the following list comprehension:

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

Output:

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

Note: this assumes you are keeping the same structure in every element of your list.

Your code overwrites first element of out every loop because you are referring to out[0] each time. Assuming you are trying to get list of unique interfaces with set IP you might want to use something like

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

'' is evaluated as False

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM