【发布时间】:2015-07-29 15:37:01
【问题描述】:
我有一个包含一些嵌套值的字典,如下所示:
my_dict = {
"id": 1,
"name": "test",
"system": "x",
"date": "2015-07-27",
"profile": {
"location": "My City",
"preferences": [
{
"code": "5",
"description": "MyPreference",
}
]
},
"logins": [
"2015-07-27 07:01:03",
"2015-07-27 08:27:41"
]
}
而且,我有一个大查询表架构,如下所示:
schema = {
"fields": [
{'name':'id', 'type':'INTEGER', 'mode':'REQUIRED'},
{'name':'name', 'type':'STRING', 'mode':'REQUIRED'},
{'name':'date', 'type':'TIMESTAMP', 'mode':'REQUIRED'},
{'name':'profile', 'type':'RECORD', 'fields':[
{'name':'location', 'type':'STRING', 'mode':'NULLABLE'},
{'name':'preferences', 'type':'RECORD', 'mode':'REPEATED', 'fields':[
{'name':'code', 'type':'STRING', 'mode':'NULLABLE'},
{'name':'description', 'type':'STRING', 'mode':'NULLABLE'}
]},
]},
{'name':'logins', 'type':'TIMESTAMP', 'mode':'REPEATED'}
]
}
我想遍历所有原始的 my_dict 并基于架构的结构构建一个新的 dict。换句话说,遍历模式并从原始 my_dict 中获取正确的值。
要像这样构建一个新的字典(请注意,架构中不存在的字段“系统”不会被复制):
new_dict = {
"id": 1,
"name": "test",
"date": "2015-07-27",
"profile": {
"location": "My City",
"preferences": [
{
"code": "5",
"description": "MyPreference",
}
]
},
"logins": [
"2015-07-27 07:01:03",
"2015-07-27 08:27:41"
]
}
如果没有嵌套字段迭代简单的 dict.items() 并复制值,这可能会更容易,但是如何构建新的 dict 以递归方式访问原始 dict?
【问题讨论】:
-
听起来您需要访问者模式的变体...oodesign.com/visitor-pattern.html
标签: python dictionary google-bigquery