gpt4 book ai didi

python : getting into imbedded document

转载 作者:太空宇宙 更新时间:2023-11-04 09:12:18 27 4
gpt4 key购买 nike

我有一个数据库“记录”,其中包含以下类型的文档:

{ ..., ..., "grades" : {"good": "40.0", "bad":"22.0"}}
  1. 我需要进入文档并将变量定义为“好”和“差”成绩的总和。
  2. 我不知道如何进入嵌入式文档,

我试过了:

for i in records:
variable = i['grade.good']

但这似乎行不通。

其次,成绩是字符串,我需要将它们转换为整数/再次尝试

total = int(i['grade.good']) + int(i['grade.bad'])

但那也错了。请注意,我的字符串是 float 帮助非常感谢!!

最佳答案

代替 i['grade.good'] 试试 i['grade']['good']

正确地从字典中检索数据

In [11]: d = {"grades" : {"good": "40", "bad":"22"}}

In [12]: d['grades']['good']
Out[12]: '40'

In [13]: total= int(d['grades']['good']) + int(d['grades']['bad'])

In [14]: total
Out[14]: 62

对于 float

In [21]: d = {"grades" : {"good": "40.0", "bad":"22.0"}}

In [22]: print float(d['grades']['good']) + float(d['grades']['bad'])
62.0

关于 python : getting into imbedded document,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13492384/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com