2

I am trying to define a dictionary wherein some key-value pairs can be specified using comprehension (because these pairs are formulaic), while others need to be specified explicitly. Due to a coding guideline restriction, the dictionary definition needs to be a single assignment statement. Therefore, no multiple assignments to compose the dictionary. Is it possible to combine explicit key-value specification along with comprehension to define the dictionary?

Minimal example:

d = {
    '0': 0x1,
    '0'*r + 'X': 0x100 + r for r in range(2), # r is much larger in real-world application
    'Y': 0xA
}

Expected output:

>>> d
    {'0': 1, 'X' = 256, '0X' = 257, 'Y' = 10}

Error:

d = {
    '0': 0x1,
    '0'*r + 'X': 0x100 + r for r in range(2),
    
SyntaxError: invalid syntax
rkshthrmsh
  • 79
  • 7

1 Answers1

3

You can merge two or more dictionaries in one expression by using the dictionary unpacking syntax ** (PEP 448), see: How do I merge two dictionaries in a single expression in Python?

d = {'0': 0x1, **inner, 'Y': 0xA}

In this case, the inner dictionary is created by a dictionary comprehension:

{'0'*r + 'X': 0x100 + r for r in range(2)}

So the resulting expression is:

d = {
    '0': 0x1,
    **{'0'*r + 'X': 0x100 + r for r in range(2)},
    'Y': 0xA
}
mkrieger1
  • 19,194
  • 5
  • 54
  • 65