0

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! :)

1 Answer 1

1

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).

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much, this first solution directly works like a charm!

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.