1

I have tried this for converting list of list to json. But Could not convert to proper json format.

My data is

    data= [['India',
          'India runs mentorship driven incubation.',
          '/7e9e130075d3bfcd9e0.png'],
         ['Capital',
          'develops high growth and market-defining India-centric Software and Services Big Data and Analytics and Consumer Mobile or Internet markets.',
          '/data/images/512bc5a2937.png']]

    titles = ['Country','description','logo']

    values = [e for g in grouper(3, data) for e in g]
keys = (titles[i%3] for i in xrange(len(values)))

objs = [dict(g) for g in grouper(3, list(izip(keys, values)))]
print(objs)

result:

[{'Country': ['India', 'India runs mentorship driven incubation.', '/7e9e130075d3bfcd9e0.png'], 'description': ['Capital', 'develops high growth and market-defining India-centric Software and Services Big Data and Analytics and Consumer Mobile or Internet markets.', '/data/images/512bc5a2937.png']}]

But expected result should be in this form.

[{'Country': 'India', 'description': 'India runs mentorship driven incubation.', 'logo': '/7e9e130075d3bfcd9e0.png'}]  

What should be reason ?

1 Answer 1

2

You can use a one-line list comprehension. First, iterate through data, an for each piece of data (entry), zip it with titles to create an iterable of tuples that can be converted into a dictionary:

data= [['India',
      'India runs mentorship driven incubation.',
      '/7e9e130075d3bfcd9e0.png'],
     ['Capital',
      'develops high growth and market-defining India-centric Software and Services Big Data and Analytics and Consumer Mobile or Internet markets.',
      '/data/images/512bc5a2937.png']]

titles = ['Country','description','logo']

result = [dict(zip(titles, entry)) for entry in data]
print(result)

Output:

[{'Country': 'India',
  'description': 'India runs mentorship driven incubation.',
  'logo': '/7e9e130075d3bfcd9e0.png'},
 {'Country': 'Capital',
  'description': 'develops high growth and market-defining India-centric Software and Services Big Data and Analytics and Consumer Mobile or Internet markets.',
  'logo': '/data/images/512bc5a2937.png'}]
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.