Ad

Convert Nested String Element Into List With One Element In Python

- 1 answer

Hope this is a simple one.

I have the following json:

{
   'listTitle': 'dsadasdsa',
   'chapters': 'testchapter',
   'sublist': [
      {
         'subListCreator': 'jan',
         'item': [
            {
               'itemTitle': 'dasdasd',
               'itemContext': 'None'
            }
         ]
      }
   ]
} 

Of which I can print my testchapter value by doing:

  print(data['chapters'])

Here's the question, I would like to do two things:

  1. Remove the complete chapters element in case there is an empty chapter-string: 'chapters': ''

  2. Convert chapters to a list containing the testchapter-value.

Desired outcome in case of scenario 1:

{
    'listTitle': 'dsadasdsa',
    'sublist': [
       {
          'subListCreator': 'jan',
          'item': [
             {
                'itemTitle': 'dasdasd',
                'itemContext': 'None'
             }
          ]
       }
    ]
 }

Desired outcome in case of scenario 2:

{
    'listTitle': 'dsadasdsa',
    'chapters': [
       'testchapter'
    ],
    'sublist': [
       {
          'subListCreator': 'jan',
          'item': [
             {
                'itemTitle': 'dasdasd',
                'itemContext': 'None'
             }
          ]
       }
    ]
 }

Tried a bunch of things but did not manage so far. Either it remained a string instead of list while looking like a list. Or all the string-characters were converted to individual list elements etc.

Hope you can help me! :)

Ad

Answer

Mutating the dict in place is the simplest way if that's an option:

if data['chapters']:
    data['chapters'] = [data['chapters']]
else:
    data.pop('chapters')

Building a new dict via a comprehension might look like:

{k: [v] if k == 'chapters' else v for k, v in data.items() if v or k != 'chapters'}

The key thing that it sounds like you weren't able to find was that to turn a single value v into a list containing that value, you want to use the list literal expression [v]. If you do list(v), you'll get a list containing each item from the iteration of v (so if v is a string, you get a list of its individual characters).

Ad
source: stackoverflow.com
Ad