I am new to python and I am having some trouble with finding a nice way to complete my task
given i have a dictionary similar to this
x = {
"rackList": [
{
"rackType": "apc",
"serverList": [
{
"serverType": "x4950",
"serverIp": "192.168.0.1",
}
],
"position": 1
},
{
"rackType": "apc",
"serverList": [
{
"serverType": "x4950",
"serverIp": "192.168.0.2",
}
],
"position": 2
},
{
"rackType": "apc",
"serverList": [
{
"serverType": "x4950",
"serverIp": "192.168.0.3",
}
],
"position": 3
},
{
"rackType": "apc",
"serverList": [
{
"serverType": "x4950",
"serverIp": "192.168.0.4",
}
],
"position": 4
}
]}
I need to extract the server IP from each serverList, so currently I am doing this:
y = []
for i in x['rackList']:
for j in i['serverList']:
y.append(j['serverIp'])
I would like to know if there is a more python like or more elagent way of achieving the same result.
Thanks in advance
Yes, it's called a list comprehension :
y = [server['serverIp'] for rack in x['rackList'] for server in rack['serverList']]
# ['192.168.0.1', '192.168.0.2', '192.168.0.3', '192.168.0.4']
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.