Home > Net >  Trying to iterate through a list of dictionaries
Trying to iterate through a list of dictionaries

Time:12-30

I have json list. I would like to iterate "PrivateIP" through a list of dirctories and append to the empty list:

here's the code:

InstanceId = []
message = [{"SNowTicket":"RITM00001","ServerIPList":[{"PrivateIP":"182.0.0.0", "HostName":"ip-182-0-0-0.ec2.internal", "Region":"us-east-1", "AccountID":"12345678"}, {"PrivateIP": "182.1.1.1", "HostName": "ip-182-1-1-1.ec2.internal", "Region": "us-east-1", "AccountID": "12345678"}],"Operation":"stop","id":"text-123"}]

for i in message:
    for key in i:
        print(key, i[key])
        instanceIds.append(privateIP)

output of the code:

It gives the values for all the keys. But i would only want the values for "ServerIPList" and iterate its values "PrivateIP"

SNowTicket RITM00001
ServerIPList [{'PrivateIP': '182.0.0.0', 'HostName': 'ip-182-0-0-0.ec2.internal', 'Region': 'us-east-1', 'AccountID': '12345678'}, {'PrivateIP': '182.1.1.1', 'HostName': 'ip-182-1-1-1.ec2.internal', 'Region': 'us-east-1', 'AccountID': '12345678'}]
Operation stop
id text-123

i want to iterate the values for "PrivateIP" inside the dict of "ServerIPList" and append their values in the empty list "InstanceIds"

InstanceId = ["182.0.0.0", "182.1.1.1"]

CodePudding user response:

I think you can just do it like this

for i in message:
    for item in i['ServerIPList']:
        instanceIds.append(item['PrivateIP'])

The outer loop iterates over the elements in the message list, and the inner loop iterates over the elements in the ServerIPList key of each dictionary. For each PrivateIP value, it is appended to the instanceIds list.

CodePudding user response:

for accessing the contents of the list message, we have to iterate through it for i in message:.

for accessing the ServerIPList in every i we have to make another for loop, i.e. for j in i['ServerIPList']

Then we can finally append the privateIP in the empty list.

The whole code for the same is as follows:

for i in message:    
    for j in i['ServerIPList']:
        InstanceId.append(j['PrivateIP'])
print(InstanceId)

CodePudding user response:

for key in message[0].keys():
    if (key == "ServerIPList"):
        for i in message[0][key]:
            for key1 in i.keys():
                if (key1 == "PrivateIP"):
                    InstanceId.append(i[key1])

print(InstanceId)
  • Related