0

How to make this script automatically concatenate the array? So that it is not necessary to pass the indices, example: arr[0] ... arr[n]. Where val1, val2 ... val(n), is automatically assigned in an increasing way, example: val1, val2, val3 ... and so on. That way the array could have N values ​​and all would be transformed into Json automatically

import json

arr = ['MyValue1', 'MyValue2']
list = [{"labels": {"val1": arr[0], "val2": arr[1]}}]

print(json.dumps(list))

Output:

{
    "labels": {
        "val1": "MyValue1",
        "val2": "MyValue2"
    }
}
9
  • 2
    That doesn't seem like a good idea. Why not store the labels as a list? Commented Aug 18, 2020 at 13:18
  • the idea is to store it in a database column in json format Commented Aug 18, 2020 at 13:19
  • suggests something different? Commented Aug 18, 2020 at 13:19
  • 2
    Why not use this JSON output instead? {"labels": ["MyValue1", "MyValue2"]} Commented Aug 18, 2020 at 13:21
  • 2
    {"labels": ["MyValue1", "MyValue2", "MyValue3"]} of course. Or in general: json.dumps({"labels": arr}). Commented Aug 18, 2020 at 13:25

1 Answer 1

2

You could use dictionary comprehension:

import json

arr = ['MyValue1', 'MyValue2']
list = [{"labels": {"val%d"%(i+1):e for i,e in enumerate(arr)}}]

print(json.dumps(list))

Alternatively:

import json

arr = ['MyValue1', 'MyValue2']
list = {"labels": arr}

print(json.dumps(list))
Sign up to request clarification or add additional context in comments.

7 Comments

Perfect, I just wanted a performatic way to do that, thanks!
No problem. An alternative would be to do something like this list = [{"labels": arr}] You can have ordered lists in json, so there isn't a need to have a new dictionary. Of course, either option is fine
Anyway, could you attach the other option to your answer? We leave it to people in the future with the same doubt to decide which approach they think is best to follow for their problem
@LuisHenrique dictionary comprehension is an extra operation and an extra data structure, so I would say it is better to just have the list in the dictionary. You could also get rid of the square brackets as Thomas suggested in their comment as you can dump a dictionary with json
@LuisHenrique I shall do
|

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.