1

I need a simple task to create a list within list in Python Here is the code I have tried

data_list = []

data = {'AgreementIdList': 'ABC123', 'Required': 'true'}

data_list.append(data)

print (data_list)

Actual Result:

[{'AgreementIdList': 'ABC123', 'Required': 'true'}]

Expected Result:

{"AgreementIdList": ["ABC123"], "Required": true}
1
  • 2
    Your expected result doesn't make sense. Why is the first value now in a sublist where the second isn't? And also changed from the string 'true' to the (incorrect capitalization) bool literal False? Commented Apr 17, 2019 at 11:11

5 Answers 5

3

Can you try the following:

data['AgreementIdList'] = [data['AgreementIdList']]
val = data['Required']
if val == 'true':
    val = True    
data['Required'] = val

Assuming you want the following output:

{"AgreementIdList": ["ABC123"], "Required": True}

Now if you want to convert it to json you need to use an additional library. The following will work:

import json
data_list = []
data_list.append(data)
json_data = json.dumps(data_list)
print(json_data)

JSON Output:

'[{"AgreementIdList": ["ABC123"], "Required": true}]'

The json output can be now used to test you API.

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

1 Comment

actually I need to pass a JSON string for testing the API and payload is having true in lower case
0

I'm assuming you don't necessarily want to mutate the original data.

data = {'AgreementIdList': 'ABC123', 'Required': 'true'}
data2 = dict(data, AgreementIdList=[data['AgreementIdList']])
print(data2)

outputs

{'AgreementIdList': ['ABC123'], 'Required': 'true'}

On more recent Python versions, you can also use this syntax for the same effect:

data = {'AgreementIdList': 'ABC123', 'Required': 'true'}
data2 = {**data, 'AgreementIdList': [data['AgreementIdList']]}

Comments

0

First of all your data is set as a dictonary. You can find this out by running print(type(data)). So what you are actually trying to do is to add a list with one item to a dictionary. Try this:

data = {'AgreementIdList': 'ABC123', 'Required': 'true'}

data['AgreementIdList'] = ['ABC123']

print(data)

Comments

0

For expected result:

data2 = {'AgreementIdList': [data['AgreementIdList']], 'Required':(data['Required']=='true')}
data2
Out[10]: {'AgreementIdList': ['ABC123'], 'Required': True}

Comments

0

You can just make below change to get expected result,

data = {'AgreementIdList': ['ABC123'], 'Required': 'true'}

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.