Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Key Value Pair output
#3
(May-02-2019, 06:06 AM)buran Wrote: It's fair to guess that rows is returned from query to database, so it is list/tuple of tuples. You need to convert it to dict, before pass to json.dumps()

import json
rows = [(1, "Apple"), (2, "Banana"), (3, "Orange")]
print(json.dumps(rows))
print(json.dumps(dict(rows)))
Output:
[[1, "Apple"], [2, "Banana"], [3, "Orange"]] {"1": "Apple", "2": "Banana", "3": "Orange"} >>>

Thanks Buran,

You are correct in that this is results from a query. The code also executes inside a AWS Lambda function.

Ive modified my code to

return {
        'statusCode': 200,
        'headers': {'Access-Control-Allow-Origin': '*',
        'Content-Type': 'application/json'},
        "body": json.dumps(dict((rows))
    }
But am getting syntax error

Im told that output should be

{
"body": [{
"Id”: "1”,
"Fruit”: "Apple”
},{
"Id”: "2”,
"Fruit”: "Banana”
}]
}
Reply


Messages In This Thread
Key Value Pair output - by UtiliseIT - May-02-2019, 05:57 AM
RE: Key Value Pair output - by buran - May-02-2019, 06:06 AM
RE: Key Value Pair output - by UtiliseIT - May-02-2019, 06:45 AM
RE: Key Value Pair output - by buran - May-02-2019, 06:59 AM
RE: Key Value Pair output - by UtiliseIT - May-02-2019, 07:00 AM
RE: Key Value Pair output - by buran - May-02-2019, 07:02 AM
RE: Key Value Pair output - by UtiliseIT - May-03-2019, 04:41 AM
RE: Key Value Pair output - by buran - May-03-2019, 07:06 AM
RE: Key Value Pair output - by UtiliseIT - May-03-2019, 07:20 AM
RE: Key Value Pair output - by buran - May-03-2019, 07:30 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Getting the maximum value:key pair from a dictionary sean1 2 1,547 Jan-17-2022, 01:04 PM
Last Post: DeaD_EyE
  How to extract specific key value pair from string? aditi06 0 2,673 Apr-15-2021, 06:26 PM
Last Post: aditi06
  Auto re-pair / re-sync Controller via Script? User3000 2 2,497 Nov-30-2020, 11:42 AM
Last Post: User3000
  team pair issue jk91 29 8,927 Mar-03-2020, 06:15 PM
Last Post: jefsummers
  Search a List of Dictionaries by Key-Value Pair; Return Dictionary/ies Containing KV dn237 19 7,148 May-29-2019, 02:27 AM
Last Post: heiner55
  Parsing Text file having repeated value key pair using python manussnair 3 3,433 Aug-04-2018, 11:48 PM
Last Post: micseydel

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020