jimmy jimmy
jimmy jimmy

Reputation: 11

iterate a dictionary inorder of elements

given

post = {"comments": [
    {
        "_id": 2, 
        "detail": "info1",
        "responses": [
            {
                "_id": 3,
                "responses": [],
                "detail": "info2"
            }]
    },
    {
        "_id": 0, 
        "responses": [],
        "detail": "info3",
    }]
}

visually this is just

[comment comment]
    [child comment]
[parent comment]

I am trying to traverse through each comment from first to last

so info1 then info2 then info3

My attempt

queue = []
comment1 = post['comments']
queue.append(comment1)
for responses in queue:
    for comment in responses:
        print(comment['detail'])
        if(comment['responses'] != []):
            queue.append(comment['responses'])

this prints

info1
info3
info2

Anyway to get what I want by tweaking this a bit?

Upvotes: 0

Views: 76

Answers (3)

kettle
kettle

Reputation: 460

The reason your code did what it did is because it added the replies at the end of the queue, instead of directly after it. To fix this you'll need to make a function:

def process_comment(comment):
    print(comment['detail'])
    if(comment['responses'] !=  []):
        for i in comment['responses']:
            process_comment(i)

queue = []
comment1 = post['comments']
queue.append(comment1)
for responses in queue:
    for comment in  responses:
        process_comment(comment)

The above code should work.

Upvotes: 0

wjandrea
wjandrea

Reputation: 32954

You can use a recursive function to walk the comment tree. Here's one way:

def replies_deep(comment):
    print(comment['detail'])
    for response in comment['responses']:  # Iterate over responses
        replies_deep(response)  # Recurse into the response's responses

for top in post['comments']:
    replies_deep(top)

Upvotes: 1

ObsoleteAwareProduce
ObsoleteAwareProduce

Reputation: 756

Try this code; it uses a recursive function to get comments:

#Bad code, but simplest in this circumstance.
def iterate(arr):
  global queue
  for comment in arr:
    queue.append(comment["detail"])
    print(comment["detail"]) #For your debug.
    iterate(comment["responses"])

post = {} #Put your data here
queue = []
iterate(post["comments"])

The function calls itself over and over, reading replies to replies until it finishes. It produces your desired result, prioritising going down trees before across.

Upvotes: 0

Related Questions