TheAlgorithms/Python · error · ValueError

{var_name} must be a dict

Error message

{var_name} must be a dict

What it means

Raised by viterbi's _validate_dict (dynamic_programming/viterbi.py:364) when one of the probability parameters (initial_probabilities, transition_probabilities, emission_probabilities, or their nested rows) is not a Python dict. These parameters are keyed by state/symbol names, so lists, strings, or numbers are rejected with the parameter name interpolated into the message.

Source

Thrown at dynamic_programming/viterbi.py:364

    Traceback (most recent call last):
            ...
    ValueError: mock_name must be a dict
    >>> _validate_dict({"a": 8}, "mock_name", dict)
    Traceback (most recent call last):
            ...
    ValueError: mock_name all values must be dict
    >>> _validate_dict({2: 0.5}, "mock_name",float, True)
    Traceback (most recent call last):
            ...
    ValueError: mock_name all keys must be strings
    >>> _validate_dict({"b": 4}, "mock_name", float,True)
    Traceback (most recent call last):
            ...
    ValueError: mock_name nested dictionary all values must be float
    """
    if not isinstance(_object, dict):
        msg = f"{var_name} must be a dict"
        raise ValueError(msg)
    if not all(isinstance(x, str) for x in _object):
        msg = f"{var_name} all keys must be strings"
        raise ValueError(msg)
    if not all(isinstance(x, value_type) for x in _object.values()):
        nested_text = "nested dictionary " if nested else ""
        msg = f"{var_name} {nested_text}all values must be {value_type.__name__}"
        raise ValueError(msg)


if __name__ == "__main__":
    from doctest import testmod

    testmod()

View on GitHub (pinned to f5988cc097)

Solutions

  1. Convert matrices to dict-of-dicts keyed by state names: {s_i: {s_j: matrix[i][j] for j, s_j in enumerate(states)} for i, s_i in enumerate(states)}.
  2. For pandas DataFrames use df.to_dict(orient='index') after ensuring column/index labels are the state names.
  3. Check each of the three probability parameters is a dict before calling.

Example fix

# before
viterbi(obs, states, initial_p, [[0.7, 0.3], [0.4, 0.6]], emit_p)  # ValueError

# after
trans_p = {'rainy': {'rainy': 0.7, 'sunny': 0.3}, 'sunny': {'rainy': 0.4, 'sunny': 0.6}}
viterbi(obs, states, initial_p, trans_p, emit_p)
Defensive patterns

Strategy: type-guard

Validate before calling

def is_prob_dict(x: object) -> bool:
    return isinstance(x, dict)

Type guard

def is_prob_dict(x: object) -> TypeGuard[dict]:
    return isinstance(x, dict)

Prevention

When it happens

Trigger: Calling viterbi with transition_probabilities=[['a',0.5]] or 'invalid' instead of {'rainy': {'rainy': 0.7, ...}}; passing a numpy 2-D matrix instead of a dict-of-dicts; passing a pandas DataFrame. The doctest shows _validate_dicts('invalid', ...) hitting exactly this path.

Common situations: Representing transition matrices as 2-D arrays from numerical code and passing them straight in; JSON configs where a nested object was flattened into a list; assuming the library accepts matrix-style HMM parameters.

Related errors


AI-assisted analysis of TheAlgorithms/Python@f5988cc097 (2026-08-14). Data as JSON: /api/errors/9339edd1fc37f61f. Report an issue: GitHub.