S Andrew
S Andrew

Reputation: 7268

How to save the elements of multidimensional list in nested json in python

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

Upvotes: 0

Views: 58

Answers (1)

jpp
jpp

Reputation: 164753

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.

Upvotes: 3

Related Questions