Python inline list formatting

Source: Internet
Author: User

A question on the StackOverflow:

Put the following format:

[{"id": 1, "title": "Node1", "parent": "NULL"},{"id": 2, "title": "Node2", "Parent": 1},{"id": 3,     "title": "Node3", "Parent": 1},{"id": 4, "title": "Node4", "Parent": 2},{"id": 5, "title": "Node5", "Parent": 2}]

Change to:

    [{       ' id ':1,       ' Title ': ' Node1 ',         ' Childs ':[            {                ' id ':2,             ' title ': ' Node2 '               ' Childs ':[                  {                      ' id ':4,                    ' title ': ' Node4 ',                    ' Childs ':  []  &NBsp;            },                {                      ' id ':5,                    ' title ': ' Node5 ',                    ' Childs ':  []               }             ]          },         {                ' id ':3,              ' title ': ' Node3 ' &NBsp;            ' Childs ':[]          }      ]   }]

Related code: (mainly using the variability of Python objects, such as dict,list are variable.) so that the depth of the data can be simplified)

result, t = [], {}for i in K: # K for the above data, K recommended to sort by parent i[' childs ' = [] if i[' parent '] = = ' null ': Del i[' parent '] result.append (i) t[1] = Result[0] else:t[i[' parent ']][' Childs '].append (i) t[i [' ID ']] = t[i[' parent ']][' Childs '][-1] del t[i[' parent ']][' Childs '][-1][' parent ']print result

Results:

z:\download>k.py[{' Childs ': [{' Childs ': [{' Childs ': [], ' ID ': 4, ' title ': ' Node4 '}, {' Childs ': [], ' ID ': 5, ' title ': ' N ' Ode5 '}], ' ID ': 2, ' title ': ' Node2 '}, {' Childs ': [], ' ID ': 3, ' title ': ' Node3 '}], ' ID ': 1, ' title ': ' Node1 '}]



Python inline list formatting

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.