2

How would I flatten this in Python so that every "widget" is an element of a list?

{  "widgets" :[{"num": "1", "letter": "a",
              "widgets" :[{"num": "2", "letter": "b",
                           "widgets" :[{"num": "3","letter": "c"},
                                       {"num": "4", "letter": "d"}]
                         }]
            }]
}

So it ends up as

[{"num":"1", "letter","a"},
 {"num": "2", "letter":"b"},
 {"num": "3", "letter":"c"},
 {"num": "4", "letter":"d"}] 
3
  • 2
    the real question is how did you get it like this in the first place Commented Jun 4, 2014 at 19:09
  • the structure was produced by someone else! Commented Jun 4, 2014 at 19:12
  • is the indenting done by someone else too? Commented Jun 4, 2014 at 19:12

3 Answers 3

4

After you shoot whoever gave you that data, maybe something like this:

def flatten_widgets(widget):
    stack = [widget['widgets']]
    while stack:
        for widget in stack.pop():
            yield {k: v for k, v in widget.items() if k != 'widgets'}
            if 'widgets' in widget:
                stack.append(widget['widgets'])

>>> list(flatten_widgets(a))

[{'letter': 'a', 'num': '1'},
 {'letter': 'b', 'num': '2'},
 {'letter': 'c', 'num': '3'},
 {'letter': 'd', 'num': '4'}]
Sign up to request clarification or add additional context in comments.

Comments

1

Here's a recursive solution:

def flatten_widget(widget):
    assert isinstance(widget, dict)

    # Remove any sub-level widgets for processing
    widgets = widget.pop('widgets', None)

    # The first object is itself, unless it contains nothing
    flat_list = [widget] if widget else []

    # If there are sub-level widgets, flatten them
    if widgets:
        assert isinstance(widgets, list)
        # Recursively flatten each widget and add it return list
        for w in widgets:
            flat_list += flatten_widget(w)

    # Return all widgets in a list
    return flat_list

print flatten_widget(widget)
# [{'num': '1', 'letter': 'a'}, {'num': '2', 'letter': 'b'}, {'num': '3', 'letter': 'c'}, {'num': '4', 'letter': 'd'}]

Note that it won't detect cycling references. Also it assumes that you don't mind the original data structure would be modified. I haven't benchmarked it but I would guess not having to copy each dict item would be a bit faster.

Comments

0

This was my hasty response; after penning, I realized it doesn't have the list items in the order you specified; however I think this might point you in the right direction vis-a-vis recursion, just as the other answers here have.

Note: did not import python module "elegance". ;)

def getflattenedwidgetlist(thislist):
    thislevellist = list()
    for dictionary in thislist:
        thisdict = dict()
        thislevellist.append(thisdict)
        for key in dictionary:
            if key != "widgets":
                thisdict[key] = dictionary[key]

        if "widgets" in dictionary:
            return getflattenedwidgetlist(dictionary["widgets"]) + [thisdict]

    return thislevellist


stuff = {
   "widgets" :[{
       "num": "1",
       "letter": "a",
       "widgets" :[{
         "num": "2",
         "letter": "b",
         "widgets" :[{
             "num": "3",
             "letter": "c"
           },
           { 
            "num": "4",
            "letter": "d"
           }]
        }]
    }] 
}

print getflattenedwidgetlist([stuff])

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.