ralhei / pyRserve

A python client for Rserve (network layer to remote R server)
Other
48 stars 13 forks source link

OrderedDict <-> TaggedList #18

Closed shapiromatron closed 2 years ago

shapiromatron commented 6 years ago

Great package. I'd like to be able to go back and forth from TaggedLists to ordered dictionaries. I was thinking that we could potentially throw a warning if the TaggedList has multiple keys the same name as such:

from pyRserve import TaggedList
from collections import OrderedDict
import warnings

class TaggedListKeyDuplicates(Warning):
    pass

class TaggedList2(TaggedList):   

    @classmethod
    def from_dict(cls, dict_):
        return TaggedList2(list(dict_.items()))        

    def asdict(self):
        if len(set(self.keys)) != len(self.keys):
            warnings.warn('Items in list have non-unique names; data may be lost', TaggedListKeyDuplicates)
        return OrderedDict(self.astuples())        

So you could use it like this:

d = TaggedList2.from_dict({'a':[1,2,3], 'b':2})
d.asdict()

If I packed this up w/ some docs and unit-tests, would you accept a PR?

ralhei commented 2 years ago

Sorry, I seemed to have missed this request. I guess this can be closed now. If not, please get back to me.