0

Im creating dict from database entries:

result = []

for row in rows:
    d = dict()
    d['first'] = row[0]
    d['second'] = row[1]

result.append(json.dumps(d, indent=3, default=str))

result:

{'first': 1, 'second': 2 }

and everything looks nice but I want to add array to this dict and it should looks like below:

{'first': 1, 'second': 2, 'third': [{'somekey': row[2]}] }

and I dont know how to handle it

result = []

for row in rows:
    d = dict()
    d['first'] = row[0]
    d['second'] = row[1]
    d['third'] = []
    d['third'][somekey] = row[2]

result.append(json.dumps(d, indent=3, default=str))
 

but it doesn't work

1
  • Note that result list will hold strings, not dict, because you dump dict to json string Commented Jan 25, 2023 at 21:09

3 Answers 3

2

Directly set the value to a list containing a dict.

d['third'] = [{'somekey': row[2]}]

This can be simplified with a list comprehension.

result = [json.dumps({'first': row[0], 'second': row[1], 'third': [{'somekey':row[2]}]},
                indent=3, default=str) for row in rows]
Sign up to request clarification or add additional context in comments.

Comments

1

it's because with a list, you can only ever set the index as an int

so you're trying to say

third = []
third['somekey'] = 'value'

so instead either make the d['third'] a dict, or if you really want it to be a list, you can do what @Unmitigated posted, or if you want to use the list in the for loop like you're doing, i'd advise to append your key:value pair in the list like this

d = {}
d['third'] = []
d['third'].append({'somekey':row[2]})

Comments

0

You can try the following:

result = []
for row in rows:

    d = dict()
    d['first'] = row[0]
    d['second'] = row[1]
    d['third'] = [{'somekey': row[2]}]
    result.append(json.dumps(d, indent=3, default=str))

Here I am creating an empty dictionary, d, and assigning values to the keys 'first' and 'second' using the values at the corresponding indices of the row list. Then it assigns a list containing a single dictionary to the key 'third', where the key of the inner dictionary is 'somekey' and the value is the value in the row list at index 2. Finally, it appends the JSON-encoded version of d to the result list.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.