[英]A more elegant way to write dictionary assignments
Because of the use of nested dictionaries, the key will be longer, so it seems redundant and inefficient.因为使用嵌套字典,key会比较长,所以显得多余,效率低下。 I want to ask if there is a more elegant, high-performance implementation.
请问有没有更优雅、高性能的实现。
Nested dictionaries嵌套字典
group = {'_meta': {'hostvars': {}}, 'all': []}
for i in range(length):
ah = value[i]
group["_meta"]["hostvars"][ah["service_deploy_name"] + ah["env"] + ah["ip"]] = {}
group["all"].append(ah["service_deploy_name"] + ah["env"] + ah["ip"])
group["_meta"]["hostvars"][ah["service_deploy_name"] + ah["env"] + ah["ip"]]["ansible_host"] = ah["ip"]
group["_meta"]["hostvars"][ah["service_deploy_name"] + ah["env"] + ah["ip"]]["project_name"] = ah["project"]
group["_meta"]["hostvars"][ah["service_deploy_name"] + ah["env"] + ah["ip"]]["type_env"] = ah["env"]
if i > 0:
if value[i]["ip"] == value[i - 1]["ip"]:
if value[i]["type"] == "thrift":
group["_meta"]["hostvars"][ah["service_deploy_name"] + ah["env"] + ah["ip"]]["delay_time"] = "5"
else:
group["_meta"]["hostvars"][ah["service_deploy_name"] + ah["env"] + ah["ip"]]["delay_time"] = "20"
else:
group["_meta"]["hostvars"][ah["service_deploy_name"] + ah["env"] + ah["ip"]]["delay_time"] = "0"
else:
group["_meta"]["hostvars"][ah["service_deploy_name"] + ah["env"] + ah["ip"]]["delay_time"] = "0"
You can pull the sames out,thus making it shorter and more readable.您可以将相同的内容拉出,从而使其更短且更具可读性。
And because dictionaries are mutable,the changes you make to the slice alse changes the main dictionary:由于字典是可变的,您对切片所做的更改也会更改主字典:
group = {'_meta': {'hostvars': {}}, 'all': []}
for i in range(length):
ah = value[i]
key=ah["service_deploy_name"] + ah["env"] + ah["ip"]
sliced=group["_meta"]["hostvars"][key]
group["_meta"]["hostvars"][key] = {}
group["all"].append(key)
sliced["ansible_host"] = ah["ip"]
sliced["project_name"] = ah["project"]
sliced["type_env"] = ah["env"]
if i > 0:
if value[i]["ip"] == value[i - 1]["ip"]:
if value[i]["type"] == "thrift":
sliced["delay_time"] = "5"
else:
sliced["delay_time"] = "20"
else:
sliced["delay_time"] = "0"
else:
sliced["delay_time"] = "0"
Use a temporary variable so the original code使用临时变量使原始代码
group["_meta"]["hostvars"][ah["service_deploy_name"] + ah["env"] + ah["ip"]]["ansible_host"] = ah["ip"]
group["_meta"]["hostvars"][ah["service_deploy_name"] + ah["env"] + ah["ip"]]["project_name"] = ah["project"]
group["_meta"]["hostvars"][ah["service_deploy_name"] + ah["env"] + ah["ip"]]["type_env"] = ah["env"]
becomes变成
t = group["_meta"]["hostvars"][ah["service_deploy_name"] + ah["env"] + ah["ip"]]
t["ansible_host"] = ah["ip"]
t["project_name"] = ah["project"]
t["type_env"] = ah["env"]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.