问题描述
鉴于以下是我从yaml文件转换而来的复杂的嵌套字典,我想查询row_1
和row_2
键的值。
这是我尝试过的:
import jmespath
import pprint
data = [
{ 'includes':
[
{
'style':
[
'css/module/sandBox/style.css','css/modules/sandBox/mobile.css'
]
},{ 'javascript':
[
'js/module/sandBox/script.js','js/module/sandBox/mobile.js'
]
}
]
},{ 'row_1':
[
{
'classes': 'my-3 text-light text-center bg-primary'
},{
'columns':
[
{
'col_1':
[
{'size': 3},{ 'classes': 'my-3 text-light ' 'text-center ' 'bg-primary'}
]
},{
'col_2':
[
{'size': 3},{ 'classes': 'my-3 text-light ' 'text-center ' 'bg-primary'},{ 'styles':
[
{
'div.summary_credit_score':
[
{
'font': '300 ' '12px ' 'open-san,' 'arial,' 'Time ' 'New ''Romance'
}
]
}
]
}
]
}
]
}
]
},{ 'row_2':
[
{
'classes': 'my-3 text-light text-center bg-primary'
},' 'Time ' 'New ''Romance'
}
]
}
]
}
]
}
]
}
]
}
]
# get row
rows = jmespath.search('[*].row_*',data)[0] # not success
pp = pprint.PrettyPrinter(indent=2)
pp.pprint(rows)
我上面的查询旨在获取字典的值,该字典的键的键以row_
开头,但不会成功。谢谢。
解决方法
据我所知,在使用 jmespath 时,不能在键名中包含通配符,只能用于处理值。
最好的办法是使用字典理解。
rows = {k:v for data_dict in data for k,v in data_dict.items() if 'row' in k}