我想要一本这样的字典:
primary = "#efefef"
style = {
"H2": {
"text-align": "center",
"color": primary
}
}
或者像这样连接更好的字典:
colors = {
"primary" : "#efefef"
}
styles = {
"H2": {
"text-align": "center",
"color": colors["primary"]
}
}
如何将样式字典与变量primary或字典颜色连接起来,以便在primary或颜色获得新值时更改字典样式?
您可以使用collections.ChainMap
来创建依赖于其他字典的映射。如果相关的键相同,则此方法有效,因此您可以使用它来解决第一个情况:
from collections import ChainMap
primary = {"color": "#efefef"}
style = {
"H2": ChainMap({"text-align": "center"}, primary),
}
print(style)
primary["color"] = "#000000"
print(style)
输出如下:
{'H2': ChainMap({'text-align': 'center'}, {'color': '#efefef'})}
{'H2': ChainMap({'text-align': 'center'}, {'color': '#000000'})}
第二种情况可以通过自定义字典类来延迟__getitem__
调用来解决:
from collections import UserDict
class LazyDict(UserDict):
def __getitem__(self, key):
return LazyItem(self.data, key)
class LazyItem:
def __init__(self, mapping, key):
self.mapping = mapping
self.key = key
@property
def value(self):
return self.mapping[self.key]
class EagerDict(dict):
def __getitem__(self, key):
obj = super().__getitem__(key)
if isinstance(obj, LazyItem):
return obj.value
return obj
colors = LazyDict({
"primary" : "#efefef",
})
styles = {
"H2": EagerDict({
"text-align": "center",
"color": colors["primary"],
}),
}
print(styles["H2"]["color"])
colors["primary"] = "#000000"
print(styles["H2"]["color"])