【发布时间】:2020-03-19 18:41:20
【问题描述】:
我有一个这样的数据列表
data = [
{
"name": "Box 0",
"type": "Box",
"vals": {
"corner1": "0,0,0",
"corner2": "0,0,5",
"rotate": "0",
"scale": "1",
"translate": "0,0,0"
}
},
{
"name": "Ovus 1",
"type": "Ovus",
"vals": {
"radiusb": "1",
"radiust": "0.5",
"rotate": "0",
"scale": "1",
"translate": "0,0,0"
}
}
]
我想创建一个表单函数
fetch_attributes(name, key)
我可以在其中给出关键属性值类型、vals 或 scale。
我的问题是 scale 属性在 vals 字典中。我可以使函数在我给出 key=type 时给我输入,当我要求 key=scale 它自动进入vals 字典。
我的方法
我使用此代码作为 name = 'Box 0' 的示例
obj = [i for i in data if i['name'] == name][0]
key_1 = "['vals']" # If I want complete dict of vals
key_2 = "['vals']['scale']" #If I want only one val out of vals
key_3 = "['type']" # If I want type
result_1 = eval('obj' + key_1)
result_2 = eval('obj' + key_2)
result_3 = eval('obj' + key_3)
我想知道是否有更好或更pythonic的方式来完成这项任务
编辑
我想要一种方法,它也将有助于或指导创建一个 edit_attributes 函数
edit_attributes(name, key, value)
【问题讨论】:
-
eval绝对不是最好的主意。您可以使用dict.get或将每个查找包装在try...except中。或者你可以简单地说if key == 'scale': # lookup from vals dict; else: # lookup from obj。 -
实际上除了 vals 之外还有很多子词典,所以使用 try except 块会在列表中的数据发生变化的情况下消除灵活性
标签: python json python-3.x dictionary