首页 > 解决方案 > Python access nested Dictionary Value

问题描述

I'm converting JSON to a dictionary and then accessing values directly. Here's the JSON:

{
  "timestamp": {
    "format": "%Y-%m-%d %H:%M:%S"
  },
  "status": {
    "grok_pattern": " status=%{NUMBER:status:int}"
  },
  "SQLite3_memory_bytes": {
    "table": "stats_memory_metrics",
    "saved_name": "sqlite3_memory_bytes"
  },
  "jemalloc_resident": {
    "table": "stats_memory_metrics"
  }
}

I can access single nested dictionaries fine but when I try to access a nested dictionary with multiple keys I get an error:

with open('/tmp/metrics.json') as json_file:
    patterns = json.load(json_file)
print(patterns['jemalloc_resident']['table'])
print(patterns['timestamp']['format'])
print(patterns['SQLite3_memory_bytes']['saved_named'])
>> stats_memory_metrics
>> %Y-%m-%d %H:%M:%S
>> Traceback (most recent call last):
>>   File "test.py", line 12, in <module>
        print(patterns['SQLite3_memory_bytes']['saved_named'])
   KeyError: 'saved_named'

How can I access the saved_named key's value?

标签: pythondictionary

解决方案


You made a typo. You put saved_named instead of saved_name.


推荐阅读