from typing import Dict
from typing import Any
import collections


def convert_dict_key(key_map: Dict[str, str],
                     dict_to_convert: Dict[str, Any],
                     keep_unmapped_keys: bool = False) -> Dict[str, Any]:
  """Convert all keys in dictionary to the new key provided in mapping.

  Args:
    key_map: A mapping from old key to new key.
    dict_to_convert: The dictionary to be converted.
    keep_unmapped_keys: Keep the key, value pair as is if not in key_map.

  Returns:
    A dictionary with the same values as dict_to_convert with the new keys
      provided in key_map.
  """
  d = collections.OrderedDict()
  for k, v in dict_to_convert.items():
    if k in key_map:
      d[key_map[k]] = v
    elif keep_unmapped_keys:
      d[k] = v
    else:
      # This will only happen when we have an invalid explain metadata.
      raise ValueError("Conversion failed. Key {} not in key map {}.".format(
          k, repr(key_map)))
  return d