Reputation: 1
Currently working on some Python scripts to interact with the Spacwalk\Satellite API. I'm able to return one piece of an array I'm looking for, but not the rest. Below is the API call I'm making in my script. (key) is the session key to authenticate with the server.
duplicates = client.system.listDuplicatesByHostname(key)
Running my script will produce the following kind of output:
print duplicates
[{'hostname': 'host01', 'systems': [{'last_checkin': <DateTime '20131231T14:06:54' at 192a908>, 'systemName': 'host01.example.com', 'systemId': 1000011017}
I can pull out the 'hostname' field using something like this:
for duplicate in duplicates:
print 'Hostname: %s' % ( duplicate.get('hostname')
But I can't retrieve any of the other items. "systems" is apparently a separate array (nested?) within the first array. I'm unsure of how to reference that second "systems" array. The API reference says the output will be in this format:
Returns:
array:
struct - Duplicate Group
string "hostname"
array "systems"
struct - system
int "systemId"
string "systemName"
dateTime.iso8601 "last_checkin" - Last time server successfully checked in
I'm not sure how to pull out the other values such as systemID, systemName. Is this considered a tuple? How would I go about retrieving these values? (I'm very new to Python, I've read about "structs" but haven't found any examples that really made sense to me.) Not necessarily looking for an answer to this exact question, but anywhere someone could point me to examples that clearly explain how to work with these kinds of arrays would be most helpful!!
Upvotes: 0
Views: 809
Reputation: 1
Thanks guys, the input provided helped me figure this out. I got the output I needed using the following:
for duplicate in duplicates:
print 'IP: ' + duplicate['ip']
for system in duplicate['systems']:
print 'SystemID: ', system['systemId'], 'Name: ', system['systemName']
Upvotes: 0
Reputation: 208615
Inside of the for loop you will have a dictionary called duplicate
that contains the keys 'hostname' and 'systems', so duplicate['hostname']
will get the hostname (a string) and duplicate['systems']
will get the systems array.
You can then access an individual element from that systesm array using indexing, for example duplicate['systems'][0]
would get the first system. However what you probably want to be doing instead is create a loop like for system in duplicate['systems']
, that way you can iterate over each system in order.
Each system
you get will be a dictionary that has the keys 'systemId', 'systemName', and 'last_checkin'.
Here is what I imagine the full code might look like:
for duplicate in duplicates:
print 'Hostname: ' + duplicate['hostname']
for system in duplicate['systems']:
print 'System ID: ' + system['systemId']
print 'System Name: ' + system['systemName']
print 'Last Checkin: ' + system['last_checkin']
I would suggest taking a look at the data structures tutorial.
Upvotes: 1