-3

Can this be written in 1 line like Perl or Php?

if color_codes.get(color) is not None:
    color = color_codes.get(color)
snh_nl
  • 2,877
  • 6
  • 32
  • 62
  • 1
    [`dict.get(key, default_value)`](https://docs.python.org/3/library/stdtypes.html#dict.get). Or [`defaultdict`](https://docs.python.org/2/library/collections.html#collections.defaultdict) – Pranav Hosangadi Nov 05 '20 at 16:58
  • The question reference has nothing to do with the question here. Why dict key? Is never how any new programmer would ask it – snh_nl Nov 09 '20 at 20:27

1 Answers1

-1

Define a key value list like so. Check the value like so color = color_codes.get(color) or color or use even shorter color_codes.get(color, color)

https://onlinegdb.com/B16pTs-KP

color_codes = { 'WHITE'         : '01', 
                'BLACK'         : '99', 
                'NAVY'          : '06', 
                'ARDESIAMEL'    : 'G2',
                'DARKKHAKI'     : '41',
                'ULTRAMARINE'   : 'M3',
                'STONERED'      : '18'}

color = 'ULTRAMARINE'
color = color_codes.get(color) or color
print(color)

color = 'DONT EXIST'                    
color = color_codes.get(color) or color
print(color)

color = 'STONERED'
color = color_codes.get(color, color)
print(color)

color = 'DONT EXIST'                    
color = color_codes.get(color, color)
print(color)
snh_nl
  • 2,877
  • 6
  • 32
  • 62