How to put comments inside a Python dictionary?

Python dictionaries support single-line comments using #, but multiline comments require special handling. You can add comments to explain dictionary keys, values, or sections within your data structure.

Single-Line Comments in Dictionaries

You can add single-line comments anywhere inside a dictionary using the # symbol ?

test_items = {
    'TestOne': 'Hello',        # Active item
    # 'TestTwo': None,         # Commented out item
    'TestThree': 'World',      # Another active item
}

print(test_items)
{'TestOne': 'Hello', 'TestThree': 'World'}

Why Multiline Comments Don't Work

Triple-quoted strings are not true comments in Python - they are string literals. Placing them inside a dictionary without assignment creates invalid syntax ?

# This will cause a SyntaxError
test_items = {
    'TestOne': 'Hello',
    """
    Some random
    multiline comment
    """
}

Alternative Approaches for Documentation

Using Multiple Single-Line Comments

config = {
    # Database configuration section
    # These settings control database connectivity
    'db_host': 'localhost',
    'db_port': 5432,
    
    # API configuration section  
    # External service endpoints
    'api_url': 'https://api.example.com',
    'timeout': 30,
}

print(config)
{'db_host': 'localhost', 'db_port': 5432, 'api_url': 'https://api.example.com', 'timeout': 30}

Using Docstrings Before Dictionary

def get_settings():
    """
    Returns application settings dictionary.
    
    Database settings control connectivity.
    API settings manage external requests.
    """
    return {
        'db_host': 'localhost',
        'api_url': 'https://api.example.com',
        'debug': True,
    }

settings = get_settings()
print(settings)
{'db_host': 'localhost', 'api_url': 'https://api.example.com', 'debug': True}

Best Practices

Approach Use Case Pros
Inline # comments Explaining individual keys Clear, concise
Block # comments Documenting sections Groups related items
Function docstrings Complex configurations Detailed documentation

Conclusion

Use single-line # comments for documenting dictionary items. For extensive documentation, combine multiple single-line comments or use function docstrings to describe the dictionary's purpose.

Updated on: 2026-03-24T20:33:02+05:30

730 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements