#997 python dict from c++ map

closed-works-for-me
szager
python (259)
5
2011-04-29
2009-02-25
H Krishnan
No

Hi,

I need to be able to pickle the result of a C++ function that returns a map<string,string>. However, using std_map.i, I get a swig proxy and not a python dict. std_list.i however returns a python sequence. Is there any way to get a python dict directly?

example.cpp

#include <string>
#include <map>
#include <list>
std::map<std::string, std::string> getMap()
{
std::map<std::string, std::string> items;
items["a"] = "z";
items["b"] = "y";
return items;
}
std::list<std::string> getList()
{
std::list<std::string> items;
items.push_back("a");
items.push_back("b");
return items;
}
example.i
=========
%module example
%{
#include <string>
#include <map>
#include <list>
extern std::map<std::string, std::string> getMap();
extern std::list<std::string> getList();
%}
%include std_string.i
%include std_map.i
%include std_list.i

%template(pairss) std::pair<std::string, std::string>;
%template(mapss) std::map<std::string, std::string>;
%template(lists) std::list<std::string>;

extern std::map<std::string, std::string> getMap();
extern std::list<std::string> getList();

python output:

>>> import example
>>> example.getMap()
<example.stringMap; proxy of <Swig Object of type 'std::map< std::string,std::string,std::less< std::string >,std::allocator< std::pair< std::string const,std::string > > > *' at 0xa75fe8> >
>>> example.getList()
('a', 'b')
>>>

Discussion

  • H Krishnan

    H Krishnan - 2009-02-25

    If I use
    %template() std::map<std::string, std::strign>;
    (i.e. don't provide a name), I get back a python dict.

    I am not sure why the behavior of std::list is different.

    You may close this. Thanks a lot.

     
  • H Krishnan

    H Krishnan - 2009-02-25

    If I use
    %template() std::map<std::string, std::strign>;
    (i.e. don't provide a name), I get back a python dict.

    I am not sure why the behavior of std::list is different.

    You may close this. Thanks a lot.

     
  • szager

    szager - 2011-04-29

    I'm hesitant to change the default behavior of the output typemaps, because I don't know whom it might affect. However, I have added a convenience method asdict() to do this for you:

    >>> example.getMap().asdict()
    {'a': 'z', 'b': 'y'}

    This is in revision 29302.

    Thanks,

    Stefan

     
  • szager

    szager - 2011-04-29
    • assigned_to: nobody --> szager
    • status: open --> closed-works-for-me
     

Log in to post a comment.

Get latest updates about Open Source Projects, Conferences and News.

Sign up for the SourceForge newsletter:





No, thanks