简体   繁体   中英

Python Dict Transform

I've been having some strange difficulty trying to transform a dataset that I have.

I currently have a dictionary coming from a form as follows:

data['content']['answers']

I would like to have the ['answers'] appended to the first element of a list like so:

data['content'][0]['answers']

However when I try to create it as so, I get an empty dataset.

data['content'] = [data['content']['answers']]

I can't for the life of me figure out what I am doing wrong.

EDIT: Here is the opening JSON

I have:

{
"content" : {
              "answers" : {
                "3" : {

But I need it to be:

    {
"content" : [
              {
                 "answers" : {
                  "3" : {

thanks

You can do what you want by using a dictionary comprehension (which is one of the most elegant and powerful features in Python.)

In your case, the following should work:

d = {k:[v] for k,v in d.items()} 

You mentioned JSON in your question. Rather than rolling your own parser (which it seems like you might be trying to do), consider using the json module.

If I've understood the question correctly, it sounds like you need data['contents'] to be equal to a list where each element is a dictionary that was previously contained in data['contents'] ?

I believe this might work (works in Python 2.7 and 3.6):

# assuming that data['content'] is equal to {'answers': {'3':'stuff'}}

data['content'] = [{key:contents} for key,contents in data['content'].items()]

>>> [{'answers': {'3': 'stuff'}}]

The list comprehension will preserve the dictionary content for each dictionary that was in contents originally and will return the dictionaries as a list.

Python 2 doc: https://docs.python.org/2/tutorial/datastructures.html#list-comprehensions

Python 3 doc: https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions

It would be best if you give us a concrete example of 'data' (what the dictionary looks like), what code you try to run, what result you get and what you except. I think I have an idea but can't be sure.

Your question isn't clear and lacks of an explicit example.

Btw, something like this can work for you?

data_list = list()
for content in data.keys():
    data_list.append(data[content])

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