如何使用data_template
中的数据自动更新result
?
我的想法是映射这样的字段:
map_fields = {
"item_name": "itemName",
"background_image": "backgroundImage",
"back_item": "backItem"
}
但我不确定如何在这种情况下迭代dict以获得例外结果
result = {
"id": 10,
"item_name": "name",
"background_image": ""
"back_item": "test",
}
data_template = {
"itemName": "",
"backgroundImage": "",
"backItem": ""
}
我的尝试:
for i in result.items():
for field in map_fields.items():
if i[0] == field[0]:
data_template[field[1]] = i[1]
print data_template
答案 0 :(得分:2)
接受的答案很好,但谦卑地说,还有改进的余地。首先,不要单独调用字典的键和值。您可以通过result.items()
在一个电话中同时执行这两项操作。因此,原始代码草稿的开头很好。
其次,执行if i in map_fields.keys()
是O(n)
,不必要的昂贵。如果你做if i in map_fields
,它不仅会变得更简单,而且会O(1)
,因此效率更高!这个技巧会使二次算法成为线性的,这显然有更好的原因。
所以,接受的答案绝对是好的,但更简单,更有效的是:
for k,v in result.items(): # Hit the dict once, and use k&v from now on
if k in map_fields: # Don't lookup "in map_fields.keys()"", it is O(n)! Lookup of "in map_fields" is O(1)
data_template[map_fields[k]] = v # Simple final assignment
任何进一步改进的评论当然都是受欢迎的。
非常快速编辑:
实际上你可以通过异常处理完全摆脱if
。
for k,v in result.items(): # Hit the result dict once, and use k&v from now on
try: data_template[map_fields[k]] = v # Will execute if k is in map_fields
except: pass # Will not do anything if k is not in map_fields
有关Python数据结构复杂性的简要指南:TimeComplexity
答案 1 :(得分:0)
使用字典map_fields
,我建议您使用以下解决方案:
result = {
"id": 10,
"item_name": "name",
"background_image": "",
"back_item": "test",
}
data_template = {
"itemName": "",
"backgroundImage": "",
"backItem": ""
}
map_fields = {
"item_name": "itemName",
"background_image": "backgroundImage",
"back_item": "backItem"
}
for i in result.keys():
if i in map_fields.keys():
data_template[map_fields[i]] = result[i]
print(data_template)