Home > Software engineering >  How to frame a dictionary or JSON using two lists in python?
How to frame a dictionary or JSON using two lists in python?

Time:12-14

I am working on Flask framework and PostgreSQL .

What I am trying to do is get the elements from the database and create a Json response with respect to the data.

The table

DATE TEXT
12-12-2022 ABC
12-12-2022 DEF
13-12-2022 GHI

Using SQL query I got the date and Test and stored it in a list

Let's say

A=["12-12-2022","12-12-2022","13-12-2022"]

B=["ABC","DEF","GHI"]

What I am trying to Achieve is that

[
   {"12-12-2022":["ABC","DEF"]},
   {"13-12-2022":["GHI"]}

]

How to achieve this? My code:

'''AFTER QUERY'''

'''row[0]=date | row[1] = text'''

text={}
date=[]
for row in cursor.fetchall():
     cdate = row[0].isoformat()
     date_split=cdate.split("T")
     cdate1=date[0]
     if row[4] is not None:
            text_output[cdate1] = row[1]
content_dict = {'Content':[{cdate1:text_res}]}
content_json = json.dumps(content_dict)
return  (json.loads(content_json))

CodePudding user response:

Use itertools.groupby to group the values by a common key, in this case the date:

import itertools
import pprint

A = ['12-12-2022', '12-12-2022', '13-12-2022']

B = ['ABC', 'DEF', 'GHI']

result = [
    {k: [g[1] for g in group]}
    for k, group in itertools.groupby(zip(A, B), key=lambda x: x[0])
]

pprint.pprint(result)

Output:

[{'12-12-2022': ['ABC', 'DEF']}, {'13-12-2022': ['GHI']}]
  • Related