I have my JSON
code below being stored in jso
variable.
jso = {
"GlossDiv": {
"title": "S",
"GlossList": {
"GlossEntry": {
"Abbrev": "ISO 8879:1986",
"GlossDef": {
"GlossSeeAlso": ["GML", "XML"]
},
"GlossSee": "markup"
}
}
}
}
Whenever I'm trying to fetch the data or iterate over the JSON Object
, it's printing the data in the reverse order i.e object
first and then the other parameters.
For eg. I execute:
>>> for k,v in jso.iteritems():
... print v
...
AND THE OUTPUT I GOT:
OUTPUT GETTING
{'GlossList': {'GlossEntry': {'Abbrev': 'ISO 8879:1986', 'GlossDef': {'GlossSeeAlso': ['GML', 'XML']}, 'GlossSee': 'markup'}}, 'title': 'S'}
It can be seen that though 'title':'S'
was written before the 'GlossList' Object
still the data is printing in the reverse order. I mean it should have:
OUTPUT EXPECTED
{ 'title': 'S', 'GlossList': {'GlossEntry': {'Abbrev': 'ISO 8879:1986', 'GlossDef': {'GlossSeeAlso': ['GML', 'XML']}, 'GlossSee': 'markup'}}}
1 Answer 1
Dictionaries in python are unordered collections:
It is best to think of a dictionary as an unordered set of key: value pairs, with the requirement that the keys are unique (within one dictionary).
But, if you've loaded json from the string, you can load it directly to the OrderedDict, see:
-
2It's also important to note that this concept extends to JSON. "An object is an unordered set of name/value pairs."Explosion Pills– Explosion Pills2013年09月15日 21:28:53 +00:00Commented Sep 15, 2013 at 21:28
-
Thanks @alecxe ! But I'm unable to use
isinstance(v,(list))
orisinstance(v,(str))
for checking the entry being a list/string when I'm iterating over OrderDict for k,v in my_ordered_dict.iteritems(): ... print k,v GlossDiv OrderedDict([(u'title', u'S'), (u'GlossList', OrderedDict([(u'GlossEntry', OrderedDict([(u'Abbrev', u'ISO 8879:1986'), (u'GlossDef', OrderedDict([(u'GlossSeeAlso', [u'GML', u'XML'])])), (u'GlossSee', u'markup')]))]))]) >>>isinstance(v,(list)) #isinstance(v,(str))softvar– softvar2013年09月15日 22:21:38 +00:00Commented Sep 15, 2013 at 22:21 -
@VarunMalhotra This requirement is not in your question. Edit your question to explain what you need.Graeme Stuart– Graeme Stuart2013年09月15日 22:27:40 +00:00Commented Sep 15, 2013 at 22:27
-
@VarunMalhotra remember, that you have nested ordered dicts.
v
infor k,v in my_ordered_dict.iteritems()
is anOrderedDict
too.alecxe– alecxe2013年09月15日 22:31:09 +00:00Commented Sep 15, 2013 at 22:31
Explore related questions
See similar questions with these tags.