假设我有以下颜色词典:
COLORS = {
"green": "\033[32m",
"yellow": "\033[33m",
}
如何为一个值分配多个键,以便用户也可以输入类似的内容?
print COLORS["yellow"]
print COLORS["color-yellow"]
print COLORS["GREEN"]
print COLORS["GreenColor"]
答案 0 :(得分:3)
使用颜色名称填充字典:
COLORS = {
"green": "\033[32m",
"yellow": "\033[33m",
}
for c in list(COLORS):
color = COLORS[c]
COLORS['color-' + c] = color
COLORS[c.upper()] = color
COLORS[c.capitalize() + 'Color'] = color
注意:使用list(..)
获取密钥副本:阻止RuntimeError: dictionary changed size during iteration
。
答案 1 :(得分:1)
不确定是否有帮助,但如果你知道这些按键,那么你可以使用如下: -
my_dict = dict.fromKeys(["yellow","color-yellow"],"\033[33m")
my_dict.update(my_dict.fromkeys(["GREEN","GreenColor"],"\033[32m"))
COLORS.update(my_dict)
<强>输出: - 强>
{&#39; green&#39;:&#39; \ x1b [32m&#39;,&#39; color-yellow&#39;:&#39; \ x1b [33m&#39;,&# 39; GREEN&#39;:&#39; \ x1b [32m&#39;, &#39; GreenColor&#39;:&#39; \ x1b [32m&#39;,&#39;黄色&#39;:&#39; \ x1b [33m&#39;}