0

I want to convert original data to array , just like the second code block.

How to remove the dictionary key of the original data?

And how to convert dictionary to array?

original data:

result = {
    'Anna': [{
            'Name': 'Anna',
            'city': 'LA',
            'activity': 'run'
        },{
            'Name': 'Anna',
            'city': 'NY',
            'activity': 'sing'
        }
    ],
    'Ken': [{
            'Name': 'Ken',
            'city': 'JP',
            'activity': 'ride'
        },{
            'Name': 'Ken',
            'city': 'WA',
            'activity': 'climb'
        }
    ]
}
result = [   
        {
            'Name': 'Anna',
            'city': 'LA',
            'activity': 'run'
        },{
            'Name': 'Anna',
            'city': 'NY',
            'activity': 'sing'
        },{
            'Name': 'Ken',
            'city': 'JP',
            'activity': 'ride'
        },
            .
            .
            .
    ]
5
  • 1
    Can you show some code that you've already tried, and where you're stuck? Commented Apr 8, 2020 at 9:10
  • What have you tried? Post your code first or we can't help you Commented Apr 8, 2020 at 9:10
  • 1
    [*itertools.chain.from_iterable(result.values())] Commented Apr 8, 2020 at 9:10
  • @GrijeshChauhan list(itertools.chain.from_iterable(result.values())) is more readable and possibly slightly more efficient. Commented Apr 8, 2020 at 9:19
  • @Błotosmętek not sure about efficiency, although list(...) version is portable across Python versions. Commented Apr 8, 2020 at 14:22

1 Answer 1

2

I like doing nested list comprehensions. The following iterates first over all values in your dictionary (a list called x) and then over each element i in the list x.

[i for x in result.values() for i in x]
Sign up to request clarification or add additional context in comments.

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.