code: def flatten_spaces(
      spaces: Iterable[Dict[str, torch.Tensor]]
  ) -> Dict[str, torch.Tensor]:
      """Merges an iterable of dictionary spaces (usually observations or actions from subsequent sub-steps)
      into a single dictionary containing all the items.
  
      If one key is present in multiple elements, its value will be present only once in the resulting dictionary,
      and all values for such key will be checked for a match.
  
      :param: Iterable of dictionary spaces (usually observations or actions from subsequent sub-steps).
      :return: One flat dictionary, containing all keys and values form the elements of the iterable.
      """
      result = dict()
  
      for space in spaces:
          for key, obs in space.items():
              # check if the heads match if strict mode
              if key in result:
                  assert result[key].shape == obs.shape
                  if isinstance(obs, np.ndarray):
                      assert np.allclose(result[key], obs), (
                          f"Tried merging observations, but values for key {key} "
                          "differ. Did you intend to stack the observations instead?"
                      )
                  else:
                      assert torch.allclose(result[key], obs), (
                          f"Tried merging observations, but values for key {key} "
                          "differ. Did you intend to stack the observations instead?"
                      )
  
              # override with newest value if already existing
              result[key] = obs
  
      return result
  
file_path: maze/maze/perception/perception_utils.py
imports: import collections
  from collections import defaultdict
  from typing import Union, Dict, Any, Callable, Sequence, Iterable
  import gym
  import numpy
  import torch
  from gym import spaces
  from maze.core.env.structured_env import StepKeyType
  from maze.core.utils.structured_env_utils import flat_structured_space
label_desc: Use image node_id 2 for calling a global function with example usage: flatten_spaces(spaces) and returns: result