我正在尝试找到一种使用Python 2.7为基于JSON的字典存储密钥的好方法。如果我像下面的代码一样将它们存储为字符串,则以后使用它们看起来非常难看。有什么更好的方法呢?
import requests
r = requests.get(urlSpecifiedAbove)
dict = r.json()
listKeys = [
"['main']['tabs']['geography']['columns']['overall_rate_performance']['title']",
"['main']['tabs']['geography']['columns']['overall_rate_performance']['revenue_vs_book_rate_revenue']"
]
myCode = 'neededValue = dict' + listKeys[0]
exec(myCode)
print neededValue
通过嵌套字典的路径是键列表。
path = ['main', 'tabs', 'geography', 'columns', 'overall_rate_performance', 'title']
您可以通过此列表一次下移一个键:
def get_value_at_path(root, path):
for key in path:
root = root[key]
return root
root = r.json()
path = ['main', 'tabs', 'geography', 'columns', 'overall_rate_performance', 'title']
needed_value = get_value_at_path(root, path)