【问题标题】:How to add array to python dict?如何将数组添加到python dict?
【发布时间】:2023-01-26 05:13:36
【问题描述】:

我从数据库条目创建字典:

result = []

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

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

结果:

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

一切看起来都不错,但我想向这个字典添加数组,它应该如下所示:

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

我不知道怎么处理

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))
 

但它不起作用

【问题讨论】:

    标签: python dictionary


    【解决方案1】:
    d['third'] = [{'somekey': row[2]}]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-29
      • 1970-01-01
      • 1970-01-01
      • 2018-12-06
      • 1970-01-01
      • 2021-07-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多