【问题标题】:How to get value of nested dictionary in Python如何在 Python 中获取嵌套字典的值
【发布时间】:2020-07-23 16:34:22
【问题描述】:

我正在尝试从嵌套字典中获取值,但我得到的字符串索引必须是整数错误。

这是我的字典

dict1 = {'ID': '123', 'Name': 'test', 'VersionId': '123423', 
          'String1': '{"key1":"value1","key2":"value2"}'}

我试图获得 value2 但失败得很惨。任何人都可以对此有所了解。

sub_dict = dict1['String1']
res = str(json.loads(sub_dict)) 
print(res['key2'])

如果我打印(res)这会打印 {'key1': 'value1', 'key2': 'value2'} 但我无法获得 value2

谢谢,

【问题讨论】:

  • 不要将其转换回带有str 的字符串。 json.loads 就是你想要的。
  • 谢谢。删除 str 并让它工作。

标签: python-3.x dictionary


【解决方案1】:

你做得太过分了。

sub_dict = dict1['String1']
res = json.loads(sub_dict)
print(res['key2'])

您不需要将 res 转换为字符串。

【讨论】:

  • 知道了。谢谢
猜你喜欢
  • 1970-01-01
  • 2022-10-07
  • 2019-03-05
  • 1970-01-01
  • 2019-06-16
  • 2021-05-10
  • 2013-08-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多