Home > OS >  How to add array to python dict?
How to add array to python dict?

Time:01-26

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

CodePudding user response:

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]

CodePudding user response:

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.

CodePudding user response:

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]})
  • Related