[英]Trying to iterate through a list of dictionaries
我有 json 列表。 我想通過目錄列表和 append 將“PrivateIP”迭代到空列表:
這是代碼:
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的代碼:
它給出了所有鍵的值。 但我只想要“ServerIPList”的值並迭代其值“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
我想在“ServerIPList”的字典中迭代“PrivateIP”的值和 append 它們在空列表“InstanceIds”中的值
InstanceId = ["182.0.0.0", "182.1.1.1"]
我想你可以這樣做
for i in message:
for item in i['ServerIPList']:
instanceIds.append(item['PrivateIP'])
外層循環遍歷消息列表中的元素,內層循環遍歷每個字典的 ServerIPList 鍵中的元素。 對於每個 PrivateIP 值,它都附加到 instanceIds 列表中。
為了訪問列表消息的內容,我們必須遍歷它for i in message:
。
為了在每個 i 中訪問 ServerIPList,我們必須創建另一個 for 循環,即for j in i['ServerIPList']
然后我們終於可以 append 空列表中的私有IP。
相同的整個代碼如下:
for i in message:
for j in i['ServerIPList']:
InstanceId.append(j['PrivateIP'])
print(InstanceId)
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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.