0

I have a list of key value pairs like this

[
    {
        "date": "2020/9/15",
        "amount": "10",
        "desc": "test 1"
    },
    {
        "date": "2020/9/16",
        "amount": "25",
        "desc": "test 2"
    }
]

And I would like to convert this into like this by Python

[
    ["date", "amount", "desc"],
    ["2020/9/15", "10", "test 1"],
    ["2020/9/16", "25", "test 2"]
]

Do I just have to make a loop to do this? Would anyone guide me a better way to do?

Thank you so much.

  • 1
    `list(dicts[0]) + [list(d.values()) for d in dicts]` works nicely (though in earlier versions of python-3, before dictionary order was stipulated, it might not work as intended). – John Coleman Sep 17 '20 at 11:55

3 Answers3

3

You could go for something like this:

lis = [
    {
        "date": "2020/9/15",
        "amount": "10",
        "desc": "test 1"
    },
    {
        "date": "2020/9/16",
        "amount": "25",
        "desc": "test 2"
    }
]

out = [list(lis[0])] + [list(dic.values()) for dic in lis]
print(out)

Output:

[['date', 'amount', 'desc'], 
['2020/9/15', '10', 'test 1'], 
['2020/9/16', '25', 'test 2']]
solid.py
  • 2,782
  • 5
  • 23
  • 30
1

Using pandas:

import pandas as pd

data = [
    {
        "date": "2020/9/15",
        "amount": "10",
        "desc": "test 1"
    },
    {
        "date": "2020/9/16",
        "amount": "25",
        "desc": "test 2"
    }
]
df = pd.DataFrame(data)
output =  [df.columns.to_list()] + df.values.tolist()

Output

[['date', 'amount', 'desc'],
['2020/9/15', '10', 'test 1'],
['2020/9/16', '25', 'test 2']]
Sebastien D
  • 4,369
  • 4
  • 18
  • 46
-1

This looks like a problem that could elegantly be handled by the dataframe handling provided by the Pandas library.

See: Convert list of dictionaries to a pandas DataFrame

Rocco Fortuna
  • 300
  • 1
  • 11
  • You can add that as a comment too – Karthik Sep 17 '20 at 11:54
  • 1
    @Karthik Thank you for the suggestion. Unfortunately the `New contributor' tag does not allow me to comment anyone else's posts, as 50 reputation is the minimum required for that action. I will keep it in mind for the future. – Rocco Fortuna Sep 17 '20 at 23:24