char** to {'':('',)}

Ignacio Vazquez-Abrams ignacio at openservices.net
Wed Aug 29 13:00:41 CEST 2001


I am using the following blecherous code to do a conversion from char*s in the
form "<a>=<b>" to the form {'<a>':(tuple of '<b>'s), ...}. I'm sure that
there's probably a more straightforward way out there. Does anyone have any
ideas as to how I can simplifiy this?

---
PyObject *MyObject_mymethod(PyObject *self, PyObject *args)
{
  MyObject *me=(MyObject *) self;
  PyObject *result=NULL, *key=NULL, *val=NULL;
  PyObject *dict=NULL, *list=NULL;
  char *str=NULL, *equals=NULL;
  int i=0;
  char **stuff;

  if (PyTuple_Size(args))
  {
    PyErr_SetString(PyExc_TypeError, "function requires no arguments");
    return NULL;
  };

  dict=PyDict_New();
  result=PyDict_New();
  if ((dict==NULL) || (result==NULL))
  {
    PyErr_SetString(MyError, "Something most blecherous happened!");
    Py_XDECREF(dict);
    Py_XDECREF(result);
    return NULL;
  };
  stuff=get_stuff(me->field);
  for (i=0; i<me->numstuff; i++)
  {
    str=strdup(stuff[i]);
    equals=strchr(str, '=');
    *equals='\0';
    val=PyString_FromString(equals+1);
    if (val==NULL)
    {
      PyErr_SetString(MyError, "Something else most blecherous happened!");
      Py_XDECREF(dict);
      Py_XDECREF(result);
      return NULL;
    };
    list=PyDict_GetItemString(dict, str);
    if (list==NULL)
    {
      list=PyList_New(0);
      if (list==NULL)
      {
        PyErr_SetString(MyError, "Yet something else most blecherous "
                                   "happened!");
        Py_XDECREF(val);
        Py_XDECREF(dict);
        Py_XDECREF(result);
        return NULL;
      };
      PyList_Append(list, val);
      Py_XDECREF(val);
      PyDict_SetItemString(dict, str, list);
      Py_XDECREF(list);
    }
    else
    {
      PyList_Append(list, val);
      Py_XDECREF(val);
    };
    free(str);
  };

  i=0;
  while(PyDict_Next(dict, &i, &key, &val))
  {
    PyDict_SetItem(result, key, PyList_AsTuple(val));
  };

  return result;
};
---

And if anyone's interested, the module itself is almost ready for its first
phase of beta testing (six more methods to go!). Once it's ready, I'll post it
somewhere and whoever wants it can grab it.

-- 
Ignacio Vazquez-Abrams  <ignacio at openservices.net>





More information about the Python-list mailing list