简体   繁体   English

如何将数组添加到 python 字典?

[英]How to add array to python dict?

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但它不起作用

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]

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.在这里,我创建了一个空字典 d,并使用行列表相应索引处的值将值分配给键“first”和“second”。 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.然后它将包含单个字典的列表分配给键'third',其中内部字典的键是'somekey',值为索引2处的行列表中的值。最后,它附加JSON编码版本d 到结果列表。

it's because with a list, you can only ever set the index as an int这是因为对于列表,您只能将索引设置为 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['third'] 成为一个字典,或者如果你真的希望它成为一个列表,你可以做@Unmitigated 发布的内容,或者如果你想像你正在做的那样在 for 循环中使用列表,我建议 append 你的键值对在列表中是这样的

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM