0

I have two list objects as follows:

list_a = [[32, 0.0], [51, 1.4]]
list_b = [["APPLE", 0.7], ["BANANA", 0.0]]

and what I get by using the following code:

def my_method (some_param: str) -> list:
    ##convert a numpy.ndarray returned by some_method() to list
    list_a = some_method().values.tolist() 
    list_b = some_method().values.tolist() 

    final_list = [["list_a", *list_a]] + [["list_b", *list_b]]
    return final_list

Current output:

[
  ["list_a", [32, 0.0], [51, 1.4]],
  ["list_b", ["APPLE", 0.7], ["BANANA", 0.0]]
]

I know that I can use some sort of a json.dump but I got errors and can't seem to figure out how to achieve it. Plus, how to add custom labels for each element within the nested list.

Desired output:

[
  ["list_a", {"room": 32, "code": 0.0}, {"room": 51, "code": 1.4}],
  ["list_b", {"fruit": "APPLE", "code": 0.7}, {"fruit": "BANANA", "code": 0.0}]
]

Note: The length of the list will always be the same and the order is also guaranteed for list_a and list_b, therefore we can for sure add these labels.

Joe Bloggr
  • 61
  • 5
  • 1
    Can you write code that turns the list `[32, 0.0]` into the dict `{"room": 32, "code": 0.0}`? If so, what exactly is preventing you from applying that logic everywhere it's needed? The output you describe is not "a json object"; JSON is **just text** that **represents** a data structure. If you want the actual data structure, the `json` library will not help you. It's important to understand Python's native data structures. – Karl Knechtel Sep 28 '22 at 18:07
  • As an aside, `[[x]] + [[y]]` could simply be `[[x], [y]]`. – Karl Knechtel Sep 28 '22 at 18:09
  • my_list_a = [] for i in list_a: x = {"room": i[0]} y = {"code": i[1]} element = (x,y) my_list_a.append(element) – Luis Alejandro Vargas Ramos Sep 28 '22 at 18:27
  • Sorry because the formatting, but the question is closed. Good luck! – Luis Alejandro Vargas Ramos Sep 28 '22 at 18:28

0 Answers0