Home > database >  Adding Keys to Dictionary from a List Python
Adding Keys to Dictionary from a List Python

Time:08-24

I have queried snowflake using python to extract 3 Columns.

The result looks like this:

[('123','',datetime.date(9999,12,31)), ('321', '981', datetime.date(9999,12,31))] 

What I want is to get a JSON with the column names. so the final output would look like this:

[{
"Number": "123",
"ExternalNumber": "",
"effective_date": "9999,12,31"
},
{
"Number": "321",
"ExternalNumber":"981",
"effective_date": "9999,12,31"
}]

The column names in Snowflake are Number, ExternalNumber and effective date.

CodePudding user response:

Use list comprehensions:

import datetime

alist = [('123', '', datetime.date(9999, 12, 31)), ('321', '981', datetime.date(9999, 12, 31))]


result = [
    {
        "Number": number,
        "ExternalNumber": external_number,
        "effective_date": str(effective_date).replace('-', ',')
    } for number, external_number, effective_date in alist
]

print(result)

Output:

[
    {'Number': '123', 'ExternalNumber': '', 'effective_date': '9999,12,31'}, 
    {'Number': '321', 'ExternalNumber': '981', 'effective_date': '9999,12,31'}
]

CodePudding user response:

If what you are looking for is a simple python function:

import datetime
def convert_function(list_of_tuple):
    list_of_dict = []
    for i in list_of_tuple:
        list_of_dict.append({
            "Number": i[0],
            "ExternalNumber": i[1],
            "effective_date": str(i[2]).replace('-', ',')
        })
  • Related