Home > other >  How to convert 1D array containing dictionaries as its values into a 2D array
How to convert 1D array containing dictionaries as its values into a 2D array

Time:10-29

I want to change the below 1D array having dictionaries as its value into 2D array. I don't want to use numpy or pandas.

array = [{"id": "123", 'name-code': 'user-1666935009', 'r.no.': '1', 'start_time': '1666955702', 'state_msg': 'Finished', 'state_details': '', 'setup_time': '2371'}]

I am expecting the output as

array = [['id','name-code','r.no.','start_time','state_msg','state_details','setup_time'],['123','user-1666935009', '1','1666955702','Finished','','2371']]

CodePudding user response:

Try:

array = [
    {
        "id": "123",
        "name-code": "user-1666935009",
        "r.no.": "1",
        "start_time": "1666955702",
        "state_msg": "Finished",
        "state_details": "",
        "setup_time": "2371",
    }
]

array = [list(array[0]), list(array[0].values())]
print(array)

Prints:

[
    [
        "id",
        "name-code",
        "r.no.",
        "start_time",
        "state_msg",
        "state_details",
        "setup_time",
    ],
    ["123", "user-1666935009", "1", "1666955702", "Finished", "", "2371"],
]

If you have more dictionaries in your list:

array = [[k for d in array for k in d], [v for d in array for v in d.values()]]
print(array)

CodePudding user response:

Create a new list that contains the two empty lists you want, then loop through original dictionary (which is the initial item in the original list, so subscript 0), and append the keys and values to the new one.

array2 = [[],[]]
for key,value in array[0].items():
    array2[0].append(key)
    array2[1].append(value)

CodePudding user response:

Here is an easy to understand way of doing this:

array = [{"id": "123", 'name-code': 'user-1666935009', 'r.no.': '1', 'start_time': '1666955702',
          'state_msg': 'Finished', 'state_details': '', 'setup_time': '2371'}]

res = []
for i in range(len(array)):
    keys = list(array[i].keys())
    values = list(array[i].values())
    res.append(keys)
    res.append(values)

print(res)
  • Related