Ethan Bierlein
Ethan Bierlein

Reputation: 3535

How can I give a dictionary value multiple keys?

Suppose I have the following dictionary of colors:

COLORS = {
    "green":  "\033[32m",
    "yellow": "\033[33m",
}

How can I assign multiple keys to one value so a user could also type something like this too?

print COLORS["yellow"]
print COLORS["color-yellow"]

print COLORS["GREEN"]
print COLORS["GreenColor"]

Upvotes: 0

Views: 85

Answers (2)

Hussain Shabbir
Hussain Shabbir

Reputation: 15035

Not sure if it helps, but if you know the keys then you can use like that below:-

my_dict = dict.fromKeys(["yellow","color-yellow"],"\033[33m")
my_dict.update(my_dict.fromkeys(["GREEN","GreenColor"],"\033[32m"))
COLORS.update(my_dict)

Output:-

{'green': '\x1b[32m', 'color-yellow': '\x1b[33m', 'GREEN': '\x1b[32m', 'GreenColor': '\x1b[32m', 'yellow': '\x1b[33m'}

Upvotes: 1

falsetru
falsetru

Reputation: 369454

Populate the dictionary with color names:

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

NOTE: use of list(..) to get a copy of keys: to prevent RuntimeError: dictionary changed size during iteration.

Upvotes: 3

Related Questions