0

I have a list which holds json objects like this

a =[{"User": "Ram","Product": "Soap","Price": "25"},
    {"User": "Ramesh","Product": "Shampoo","Price": "5"},
    {"User": "Ramesh","Product": "powder","Price": "35"}]

Now I want to split this single list into multiple list like this

a2 = [
      [{"User": "Ram","Product": "Soap","Price": "25"}],
      [{"User": "Ramesh","Product": "Shampoo","Price": "5"}],
      [{"User": "Ramesh","Product": "powder","Price": "35"}]
     ]

Can anyone tell me how I can achieve this solution, I am new to python.

1
  • I'm curious as to why you want these one-element lists. Commented Dec 31, 2015 at 6:10

4 Answers 4

3

Just wrap each item in brackets:

a2 = [[item] for item in a]
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks it worked. Just out of curiosity is there a simpler way like this to do the vice-versa
Sure; a3 = [item[0] for item in a2].
3

Do like this,

[[i] for i in a]

Comments

0

Another solution,

new_a = map(lambda x: [x], a)

Output

[[{'Product': 'Soap', 'User': 'Ram', 'Price': '25'}], [{'Product': 'Shampoo', 'User': 'Ramesh', 'Price': '5'}], [{'Product': 'powder', 'User': 'Ramesh', 'Price': '35'}]]

Comments

-1

This is a more verbose way to do it without the list comprehension from Avinash's answer.

def list_split(a):
    sp = []
    for element in a:
        sp.append([element])
    return sp

a2 = list_split(a)

2 Comments

The readability of comprehensions is a matter of perspective/opinion.
Correct, that does not read the way I intended it to, replace readable with verbose. Apologies.

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.