0

I have a multidimensional list which looks like below:

[
   ['Name1','5','6','7'],
   ['Name2','3','8','5'],
]

As you can see, in the above multidimensional list, we have two lists with two names and their values. This generated by an algorithm which can generate more names like 4 names thus, there might be 4 lists inside the multidimensional list.

Based on this I have to save the above info in a json, which looks like below:

{
    "id": "id",
    "Values": [
        {
            "Name": "Name1",
            "X": "85",
            "Y": "78",
            "Z": "10"
        },
        {
            "Name": "Name2",
            "X": "85",
            "Y": "78",
            "Z": "10"
        }

    ]
}

So all the name will go inside ['Values']['Name'] followed by the int numbers but I am getting confused as to how to save list items in json as it is not fixed. can anyone help me on this.

Thanks

1 Answer 1

3

Using a list comprehension:

L = [['Name1','5','6','7'],
     ['Name2','3','8','5']]

keys = ('Name', 'X', 'Y', 'Z')

d = {**{'id': 'id'},
     **{'Values': [dict(zip(keys, i)) for i in L]}}

Result

print(d)

{'Values': [{'Name': 'Name1', 'X': '5', 'Y': '6', 'Z': '7'},
            {'Name': 'Name2', 'X': '3', 'Y': '8', 'Z': '5'}],
 'id': 'id'}

Explanation

  • The syntax {**d1, **d2} is used to combine two dictionaries.
  • dict(zip(keys, i)) creates a dictionary mapping the items in keys to the elements of i, aligning by index.
  • A list comprehension is used to iterate over sublists in L.
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you very much. But can you explain a bit. I didn't get what you are doing in the code
@SAndrew, Sure, I've added an explanation.

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.