简体   繁体   中英

Converting a python dictionary to a JSON - like object

I know this is going to sound like I just need to use json.loads from the title. But I don't think that's the case here. Or at least I should be able to do this without any libraries (plus I want to understand this and not just solve it with a library method).

What I have currently is a dictionary where the keys are words and the values are total counts for those words:

myDict = { "word1": 12, "word2": 18, "word3": 4, "word4": 45 }

and so on...

what I want is for it to become something like the following (so that I can insert it into a scraperwiki datastore):

myNewDict = {"entry": "word1", "count": 12, "entry": "word2", "count": 18, "entry": "word3", "count": 4, "entry": "word4", "count": 45}

I figured I could just loop over myDict and insert each key/value after my new chosen keys "entry" and "count" (like so):

for k, v in myDict.iteritems():
    myNewDict = { "entry": k, "count": v }

but with this, myNewDict is only saving the last result (so only giving me myNewDict={"entry":"word4", "total":45}

what am I missing here?

What you need is a list :

entries = []

for k, v in myDict.iteritems():
   entries.append({ "entry": k, "count": v })

Or even better with list comprehensions:

entries = [{'entry': k, 'count': v} for k, v in myDict.iteritems()]

In more details, you were overriding myDict at each iteration of the loop, creating a new dict every time. In case you need it, you could can add key/values to a dict like this :

myDict['key'] = ...

.. but used inside a loop, this would override the previous value associated to 'key', hence the use of a list. In the same manner, if you type:

myNewDict = {"entry": "word1", "count": 12, "entry": "word2", "count": 18, "entry": "word3", "count": 4, "entry": "word4", "count": 45}

you actually get {'count': 45, 'entry': 'word4'} !

Note: I don't know what's the expected format of the output data but JSON-wise, a list of dicts should be correct (in JSON keys are unique too I believe).

While it's not clear 100% clear what output you want, if you want just a string in the format you've outlined above, you could modify your loop to be of the form:

myCustomFormat = '{'
for k, v in myDict.iteritems():
    myCustomFormat += '"entry": {0}, "count": {1},'.format(k, v)
# Use slice to trim off trailing comma
myCustomFormat = myCustomFormat[:-1] + '}'

That being said, this probably isn't what you want. As others have pointed out, the duplicative nature of the "keys" will make this somewhat difficult to parse.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM