【问题标题】:can't get the value of something in a dict with a key无法使用键获取 dict 中某些内容的值
【发布时间】:2020-03-19 17:54:04
【问题描述】:

所以我有这个代码

test = json.load(open('data.json'))
print (test)
print(test[MACadress])

我无法获取 MACadress 的值,我已经尝试过 test.get(MACadress)

我得到这个错误:

//这是测试:

{'MACadress': '0x1c1bb5d3ce17', 'daate': '2020-03-19 17:33:19.715129', 'CPU': 2051.929375, 'mem': 26.0, 'disk': 57.1, 'process' : 333, '用户': '1'}

//错误信息:

Traceback(最近一次调用最后一次): 文件“recepteur_infos_machines.py”,第 11 行,在 打印(测试[MACadress]) NameError: 名称 'MACadress' 未定义

【问题讨论】:

  • 您需要引用'MACadress'
  • json.load 将返回一个类似dict的python对象。要获得价值,您需要像使用任何 dict 一样使用它。所以试试test['MACadress'] - 注意键周围的引号。

标签: python dictionary get


【解决方案1】:

print(test["MACadress"]) 键是一个字符串。如果没有引号,您将引用一个不存在的变量。

【讨论】:

  • 谢谢!但现在我无法在我的表中插入我的数据我收到这个错误:sqlite3.ProgrammingError:提供的绑定数量不正确。当前语句使用 7,提供了 14 个。我的意思是我不明白为什么它说我提供 14 个绑定 c.executemany('INSERT INTO infos (MACadress, daate, CPU, mem, disk, process, users) VALUES (?,?,?,?,?, ?,?)',(test.get("MACadress"),test.get("daate"),test.get("CPU"),test.get("mem"),test.get("disk" ),test.get("process"),test.get("users"))) 也许它计算了 7 个“?” + 我提交了什么?
  • 单独提问。
【解决方案2】:

您需要用连字符包围 MACadress,以便 python 将其视为字符串。 也就是说,代码应该是:

test = json.load(open('data.json'))

打印(测试)

打印(测试['MACadress'])

【讨论】:

    【解决方案3】:

    本例中的字典键是一个字符串。 (不带引号的单词是python中的变量)

    所以如果你写以下内容:

    print(test['MACadress'])

    它应该打印出字符串:'0x1c1bb5d3ce17'

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多