1

I have a loop printing a variable and I get this as a result:

{u'jsonrpc': u'2.0', u'result': [{u'hostid': u'000001'}], u'id': 132}

I really only want the host id which in this case is: 000001

Within the python script I am running I have it saved like this:

resultID = {u'jsonrpc': u'2.0', u'result': [{u'hostid': u'000001'}], u'id': 132}

print resultID

Is there anything I can do to only print out the hostid?

As a side not the hostid's are not always the same length.

Som3guy
  • 57
  • 1
  • 9
  • You are printing a python dictionary. What have you researched to not parse, but "traverse / access" it? – OneCricketeer Aug 31 '16 at 18:27
  • 6
    http://stackoverflow.com/questions/5404665/accessing-elements-of-python-dictionary – myaut Aug 31 '16 at 18:27
  • `d['result'][0]['hostid']` -> to access the value, assuming the structure is consistent amongst the variables? – ospahiu Aug 31 '16 at 18:29
  • `print resultID['result'][0]['hostid']` is what you need. You lookup the value of the `result` in the dictionary, then you lookup the first index - indicated by `0` in the list - to get the internal dictionary, and then you lookup `hostid` in that dictionary. It's not that hard. – Akshat Mahajan Aug 31 '16 at 18:29
  • Thank you so much, sorry I have one day of experience with python and was not even sure how to research this. I spent the last hour looking through .split and regex stuff. Thanks again. – Som3guy Aug 31 '16 at 18:32
  • 1
    the very well written Python [docs](https://docs.python.org/2/index.html) are your friend. In particular the [Tutorial's](https://docs.python.org/2/tutorial/index.html) chapter on [data structures](https://docs.python.org/2/tutorial/datastructures.html), specifically on [lists](https://docs.python.org/2/tutorial/introduction.html#lists) and [dictionaries](https://docs.python.org/2/tutorial/datastructures.html#dictionaries) – miraculixx Aug 31 '16 at 18:33

1 Answers1

0

Assuming your data structure is consistent:

>>> d['result'][0]['hostid']
000001
ospahiu
  • 3,465
  • 2
  • 13
  • 24