1

I have a piece of code that allows me to print dictionary items returned using .json() method on an XHR response from a website:

teamStatDicts = responser[u'teamTableStats']
for statDict in teamStatDicts:
    print("{seasonId},{tournamentRegionId},{minsPlayed},"
            .decode('cp1252').format(**statDict))

This prints in the following format:

9155,5,900
9155,5,820
...
...
...
9155,5,900
9155,5,820         

The above method works fine, providing the keys in the dictionary never change. However in some of the XHR submissions I am making they do. Is there a way that I can print all dictionary values in exactly the same format as above? I've tried a few things but really didn't get anywhere.

1 Answer 1

2

In general, give a dict, you can do:

print(','.join(str(v) for v in dct.values()))

The problem here is you don't know the order of the values. i.e. is the first value in the CSV data the seasonId? Is the the tournamentRegionId? the minsPlayed? Or is it something else entirely that you don't know about?

So, my point is that unless you know the field names, you can't put them in a string in any reliable order if the data comes to you as vanilla dicts.

If you're decoding the XHR elsewhere using json, you could make the object_pairs_hook an OrderedDict:

from collections import OrderedDict
import json

...
data = json.loads(datastring, object_pairs_hook=OrderedDict)

Now the data is guaranteed to be in the same order as the datastring was, but that only helps if the data in datastring was ordered in a particular way (which is usually not the case).

1
  • hi, thanks for replying. i have 23 separate XHR requests that i know the content of, but where only certain dictionary items are universal and where the order changes of the keys. i've decided just to hard code 23 different statements like the one in my question to get everything I want and in the right order. It's not ideal, but it will have to do.
    – gdogg371
    Nov 7, 2014 at 0:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.