CareFree
CareFree

Reputation: 311

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

Upvotes: 1

Views: 2043

Answers (4)

DiphthongException
DiphthongException

Reputation: 121

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

Upvotes: 2

John Coleman
John Coleman

Reputation: 51998

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.

Upvotes: 3

user5545873
user5545873

Reputation:

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])

Upvotes: 0

Brendan Donegan
Brendan Donegan

Reputation: 67

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.

Upvotes: 0

Related Questions