title: Converting an RPy2 ListVector to a Python dictionary
body: <p>The natural Python equivalent to a named list in R is a dict, but <a href="http://rpy.sourceforge.net/">RPy2</a> gives you a <a href="http://rpy.sourceforge.net/rpy2/doc-2.3/html/vector.html?highlight=listvector#rpy2.robjects.vectors.ListVector">ListVector</a> object.</p>
  
  <pre><code>import rpy2.robjects as robjects
  
  a = robjects.r('list(foo="barbat", fizz=123)')
  </code></pre>
  
  <p>At this point, a is a <a href="http://rpy.sourceforge.net/rpy2/doc-2.3/html/vector.html?highlight=listvector#rpy2.robjects.vectors.ListVector">ListVector</a> object.</p>
  
  <pre><code>&lt;ListVector - Python:0x108f92a28 / R:0x7febcba86ff0&gt;
  [StrVector, FloatVector]
    foo: &lt;class 'rpy2.robjects.vectors.StrVector'&gt;
    &lt;StrVector - Python:0x108f92638 / R:0x7febce0ae0d8&gt;
  [str]
    fizz: &lt;class 'rpy2.robjects.vectors.FloatVector'&gt;
    &lt;FloatVector - Python:0x10ac38fc8 / R:0x7febce0ae108&gt;
  [123.000000]
  </code></pre>
  
  <p>What I'd like to have is something I can treat like a normal Python dictionary. My temporary hack-around is this:</p>
  
  <pre><code>def as_dict(vector):
      """Convert an RPy2 ListVector to a Python dict"""
      result = {}
      for i, name in enumerate(vector.names):
          if isinstance(vector[i], robjects.ListVector):
              result[name] = as_dict(vector[i])
          elif len(vector[i]) == 1:
              result[name] = vector[i][0]
          else:
              result[name] = vector[i]
      return result
  
  as_dict(a)
  {'foo': 'barbat', 'fizz': 123.0}
  
  b = robjects.r('list(foo=list(bar=1, bat=c("one","two")), fizz=c(123,345))')
  as_dict(b)
  {'fizz': &lt;FloatVector - Python:0x108f7e950 / R:0x7febcba86b90&gt;
   [123.000000, 345.000000],
   'foo': {'bar': 1.0, 'bat': &lt;StrVector - Python:0x108f7edd0 / R:0x7febcba86ea0&gt;
    [str, str]}}
  </code></pre>
  
  <p>So, the question is... Is there a better way or something built into RPy2 that I should be using?</p>