def safe_dict_set_value(tree_node, key, value):
  """Safely set a value to a node in a tree read from JSON or YAML.

  The JSON and YAML parsers returns nodes that can be container or non-container
  types.  This method internally checks the node to make sure it's a dictionary
  before setting for the specified key.  If value is None, try to remove key
  from tree_node.

  Args:
    tree_node: Node to set.
    key: Key of the entry to be added to the node.
    value: Value of the entry to be added to the node. If None, try to remove
      the entry from tree_node.

  Returns:
    Return tree_node
  """
  if not issubclass(tree_node.__class__, dict):
    return tree_node

  if value is None:
    if key in tree_node:
      del tree_node[key]
  else:
    tree_node[key] = value

  return tree_node