|
From: Heshan S. <hes...@gm...> - 2008-04-23 12:06:30
|
Hi,
I am using java.util.map to store some data ( one key and two value
pairs , per row ) and return it to a python function . What kind of a data
structre should I use to catch it , inside python .
thanx
--
Regards,
Heshan Suriyaarachchi
|
|
From: Jeff E. <jem...@fr...> - 2008-04-23 14:29:22
|
In Jython, Java maps work mostly like Python dicts. Heshan Suriyaarachchi wrote: > Hi, > I am using java.util.map to store some data ( one key and two value > pairs , per row ) and return it to a python function . What kind of a data > structre should I use to catch it , inside python . > thanx > > > > ------------------------------------------------------------------------ > > ------------------------------------------------------------------------- > This SF.net email is sponsored by the 2008 JavaOne(SM) Conference > Don't miss this year's exciting event. There's still time to save $100. > Use priority code J8TL2D2. > http://ad.doubleclick.net/clk;198757673;13503038;p?http://java.sun.com/javaone > > > ------------------------------------------------------------------------ > > _______________________________________________ > Jython-users mailing list > Jyt...@li... > https://lists.sourceforge.net/lists/listinfo/jython-users |
|
From: David H. <dav...@gm...> - 2008-04-23 15:28:32
|
On Wed, Apr 23, 2008 at 7:06 AM, Heshan Suriyaarachchi
<hes...@gm...> wrote:
> Hi,
> I am using java.util.map to store some data ( one key and two value
> pairs , per row ) and return it to a python function . What kind of a data
> structre should I use to catch it , inside python .
If you return a java.util.Map, your Python code will get a
java.util.Map, and you can operate on it just like you would in Java.
You can call containsKey, containsValue, entrySet, get, put, and all
the other Map operations. Jython also lets you use Python syntax for
lookup and iteration on a Map:
>>> from java.util import HashMap
>>> h1 = HashMap()
>>> h1['foo'] = 'bar'
>>> h1['foo']
'bar'
>>> 'foo' in h1
1
>>> h1.containsKey('foo')
1
>>> for k in h1:
... print '%s -> %s' % (k, h1[k])
...
foo -> bar
>>>
However, looking up a key that isn't there results in different
behavior in Maps and dicts:
>>> h1['baz']
>>> h2 = {}
>>> h2['baz']
Traceback (innermost last):
File "<console>", line 1, in ?
KeyError: baz
>>>
The Map returns a null value, but the dict throws an exception. So,
unfortunately, most real Python code that is written for a dict will
not work for a Map, and vice-versa. It may appear to work if you
don't store null values and don't do any lookups that fail, but at the
very least the error-checking will be broken. But everything will be
okay if you always know which type you're dealing with, Map or dict.
- David
|
|
From: Heshan S. <hes...@gm...> - 2008-04-25 09:47:06
|
Hi,
I am trying to execute the below java code.But when I try to assign the
dictionary to map it gives an classcast exception as below
Exception in thread "main" java.lang.ClassCastException:
org.python.core.PyDictionary cannot be cast to java.util.Map
# myfile.py
# method which returns a Dictionary
def getDictionary():
Dictionary2 = {}
Dictionary2['add'] = {'returns': 'int', 'operationName': 'add', 'var1':
'integer', 'var2': 'integer'}
Dictionary2['deduct'] = {'returns': 'double', 'operationName': 'deduct',
'var1': 'integer', 'var2': 'integer'}
Dictionary2['f'] = {'a': 'double', 'returns': 'double', 'operationName':
'f'}
return Dictionary2
# test.java
# main method which calls the above method
public static void main(String args []) throws PyException {
System.out.println("testing 123");
PySystemState.initialize();
PythonInterpreter interp = new PythonInterpreter();
interp.exec("import sys");
interp.exec("print sys.path");
String str3 =
"/home/heshan/workspace/IdeaProjects/PYtest/src/essentialScripts/myfile.py";
interp.execfile(str3);
PyObject obj = interp.eval("getDictionary()");
Map map = (Map) obj;
Iterator k = map.keySet().iterator();
while (k.hasNext()) {
String key = (String) k.next();
System.out.println("Key " + key + "; Value " +
(String) map.get(key));
}
}
|
|
From: David H. <dav...@gm...> - 2008-04-25 15:12:09
|
On Fri, Apr 25, 2008 at 4:47 AM, Heshan Suriyaarachchi
<hes...@gm...> wrote:
> Hi,
> I am trying to execute the below java code.But when I try to assign the
> dictionary to map it gives an classcast exception as below
>
> Exception in thread "main" java.lang.ClassCastException:
> org.python.core.PyDictionary cannot be cast to java.util.Map
Correct; Jython does not automatically convert the dict to a Map or
automatically provide a Map facade. For interoperation between Python
and Java, you will have to do the conversion yourself, or use HashMap
for any map object that might be returned to Java code. For example:
from java.util import HashMap
# myfile.py
# method which returns a Dictionary
def getDictionary():
Dictionary2 = HashMap()
etc.
-David
|
|
From: Jeff E. <jem...@fr...> - 2008-04-25 15:33:29
|
That's correct, unfortunately PyDictionary does not
implement java.util.Map.
You need to copy the dictionary to a Java map before
passing it to Java code.
def dictToJavaMap(dict):
import java
javaMap =java.util.HashMap()
for i in dict.items():
javaMap[i[0]]=i[1]
return javaMap
Heshan Suriyaarachchi wrote:
> Hi,
> I am trying to execute the below java code.But when I try to assign the
> dictionary to map it gives an classcast exception as below
>
> Exception in thread "main" java.lang.ClassCastException:
> org.python.core.PyDictionary cannot be cast to java.util.Map
>
>
> # myfile.py
> # method which returns a Dictionary
> def getDictionary():
> Dictionary2 = {}
> Dictionary2['add'] = {'returns': 'int', 'operationName': 'add', 'var1':
> 'integer', 'var2': 'integer'}
> Dictionary2['deduct'] = {'returns': 'double', 'operationName': 'deduct',
> 'var1': 'integer', 'var2': 'integer'}
> Dictionary2['f'] = {'a': 'double', 'returns': 'double', 'operationName':
> 'f'}
> return Dictionary2
>
> # test.java
> # main method which calls the above method
> public static void main(String args []) throws PyException {
> System.out.println("testing 123");
> PySystemState.initialize();
> PythonInterpreter interp = new PythonInterpreter();
> interp.exec("import sys");
> interp.exec("print sys.path");
>
> String str3 =
> "/home/heshan/workspace/IdeaProjects/PYtest/src/essentialScripts/myfile.py";
> interp.execfile(str3);
> PyObject obj = interp.eval("getDictionary()");
> Map map = (Map) obj;
>
> Iterator k = map.keySet().iterator();
> while (k.hasNext()) {
> String key = (String) k.next();
> System.out.println("Key " + key + "; Value " +
> (String) map.get(key));
> }
> }
>
>
>
> ------------------------------------------------------------------------
>
> -------------------------------------------------------------------------
> This SF.net email is sponsored by the 2008 JavaOne(SM) Conference
> Don't miss this year's exciting event. There's still time to save $100.
> Use priority code J8TL2D2.
> http://ad.doubleclick.net/clk;198757673;13503038;p?http://java.sun.com/javaone
>
>
> ------------------------------------------------------------------------
>
> _______________________________________________
> Jython-users mailing list
> Jyt...@li...
> https://lists.sourceforge.net/lists/listinfo/jython-users
|
|
From: Heshan S. <hes...@gm...> - 2008-04-28 06:08:33
|
On Fri, Apr 25, 2008 at 9:03 PM, Jeff Emanuel <jem...@fr...> wrote:
> That's correct, unfortunately PyDictionary does not
> implement java.util.Map.
>
> You need to copy the dictionary to a Java map before
> passing it to Java code.
>
> def dictToJavaMap(dict):
> import java
> javaMap =java.util.HashMap()
> for i in dict.items():
> javaMap[i[0]]=i[1]
> return javaMap
>
> Hi Jeff,
I used the method above to convert the Dictionary to a Map. When
the method returns a javaMap , I am collecting it using a PyObject (within
my java code).Therefore I have to convert it to a Map.At that moment it
gives a class cast exception. Is there an alternative way of doing this
correctly?
PySystemState.initialize();
PythonInterpreter interp = new PythonInterpreter();
interp.exec("import sys");
interp.exec("print sys.path");
String str3 =
"/home/heshan/workspace/IdeaProjects/PYtest/src/essentialScripts/myfile.py";
interp.execfile(str3);
PyObject obj = interp.eval("getDictionary()");
String str4 = "dictToJavaMap(" + obj + ")";
PyObject obj2 = interp.eval(str4);
//aDictionary[k].get('operationName')
//String str = "" + obj + "[].get('operationName')";
//interp.exec(str);
Map map = (Map) obj2;
/*
The above line gives a exception like below
Exception in thread "main" java.lang.ClassCastException:
org.python.core.PyJavaInstance cannot be cast to java.util.Map
*/
Iterator k = map.keySet().iterator();
while (k.hasNext()) {
String key = (String) k.next();
System.out.println("Key " + key + "; Value " +
(String) map.get(key));
}
Thanx in advance
--
Regards,
Heshan Suriyaarachchi
|
|
From: Heshan S. <hes...@gm...> - 2008-04-28 09:00:47
|
Hi,
I did the following and it works fine. Thank you for all you guys for
your valuable advice and guidance.
System.out.println("testing 123");
PySystemState.initialize();
PythonInterpreter interp = new PythonInterpreter();
interp.exec("import sys");
interp.exec("print sys.path");
String str3 =
"/home/heshan/workspace/IdeaProjects/PYtest/src/essentialScripts/myfile.py";
interp.execfile(str3);
PyObject obj = interp.eval("getDictionary()");
String str4 = "dictToJavaMap(" + obj + ")";
PyObject obj2 = interp.eval(str4);
HashMap map = (HashMap) obj2.__tojava__(HashMap.class);
Iterator k = map.keySet().iterator();
while (k.hasNext()) {
String key = (String) k.next();
System.out.println("Key " + key + " === Value " +
/*(String)*/ map.get(key));
}
--
Regards,
Heshan Suriyaarachchi
|
|
From: Jeff E. <jem...@fr...> - 2008-04-28 15:11:52
|
This should work:
Map map = (Map)(interp.eval("dictToJavaMap(getDictionary())").__tojava__(Map.class));
Heshan Suriyaarachchi wrote:
> On Fri, Apr 25, 2008 at 9:03 PM, Jeff Emanuel <jem...@fr...> wrote:
>
>> That's correct, unfortunately PyDictionary does not
>> implement java.util.Map.
>>
>> You need to copy the dictionary to a Java map before
>> passing it to Java code.
>>
>> def dictToJavaMap(dict):
>> import java
>> javaMap =java.util.HashMap()
>> for i in dict.items():
>> javaMap[i[0]]=i[1]
>> return javaMap
>>
>> Hi Jeff,
> I used the method above to convert the Dictionary to a Map. When
> the method returns a javaMap , I am collecting it using a PyObject (within
> my java code).Therefore I have to convert it to a Map.At that moment it
> gives a class cast exception. Is there an alternative way of doing this
> correctly?
>
>
> PySystemState.initialize();
> PythonInterpreter interp = new PythonInterpreter();
> interp.exec("import sys");
> interp.exec("print sys.path");
>
> String str3 =
> "/home/heshan/workspace/IdeaProjects/PYtest/src/essentialScripts/myfile.py";
> interp.execfile(str3);
> PyObject obj = interp.eval("getDictionary()");
>
> String str4 = "dictToJavaMap(" + obj + ")";
> PyObject obj2 = interp.eval(str4);
>
> //aDictionary[k].get('operationName')
> //String str = "" + obj + "[].get('operationName')";
> //interp.exec(str);
>
> Map map = (Map) obj2;
> /*
> The above line gives a exception like below
> Exception in thread "main" java.lang.ClassCastException:
> org.python.core.PyJavaInstance cannot be cast to java.util.Map
> */
> Iterator k = map.keySet().iterator();
> while (k.hasNext()) {
> String key = (String) k.next();
> System.out.println("Key " + key + "; Value " +
> (String) map.get(key));
> }
>
>
> Thanx in advance
>
>
> ------------------------------------------------------------------------
>
> -------------------------------------------------------------------------
> This SF.net email is sponsored by the 2008 JavaOne(SM) Conference
> Don't miss this year's exciting event. There's still time to save $100.
> Use priority code J8TL2D2.
> http://ad.doubleclick.net/clk;198757673;13503038;p?http://java.sun.com/javaone
>
>
> ------------------------------------------------------------------------
>
> _______________________________________________
> Jython-users mailing list
> Jyt...@li...
> https://lists.sourceforge.net/lists/listinfo/jython-users
|
|
From: Tim G. <ti...@sk...> - 2008-04-30 22:26:35
|
On a more general note about this dict versus Map stuff, can anyone explain why the jython dict class doesn't simply implement java.lang.Map? It seems like such an obvious thing to do that I'm sure there must be good reason why it hasn't been done, but I don't know what that reason is. Off the top of my head I can't think of any functionality from the java version that the python version lacks, though. Thanks Tim |
|
From: David H. <dav...@gm...> - 2008-05-08 22:05:04
|
I can think of one thing that would be awkward from a backwards compatibility standpoint. Currently, if m is a Map that does not contain "foo" as a key, then in Python code m['foo'] returns None. If m is a dict that does not contain "foo" as a key, then m['foo'] throws a KeyError. So, if m is a Map *and* a dict, what does m['foo'] do? There may be existing code written to handle both Maps and dicts that tests whether m is a Map and then uses m[k] == None to test whether k is in m. It's not the best way to implement this functionality, and it's wrong if k is mapped to null, but I imagine such code exists and works fine in the field. Personally, I say breaking this is worth it, but opinions will differ, I'm sure. -David On Wed, Apr 30, 2008 at 5:26 PM, Tim Gilbert <ti...@sk...> wrote: > On a more general note about this dict versus Map stuff, can anyone > explain why the jython dict class doesn't simply implement > java.lang.Map? It seems like such an obvious thing to do that I'm sure > there must be good reason why it hasn't been done, but I don't know what > that reason is. Off the top of my head I can't think of any > functionality from the java version that the python version lacks, though. > > Thanks > Tim > > > > > > > ------------------------------------------------------------------------- > This SF.net email is sponsored by the 2008 JavaOne(SM) Conference > Don't miss this year's exciting event. There's still time to save $100. > Use priority code J8TL2D2. > http://ad.doubleclick.net/clk;198757673;13503038;p?http://java.sun.com/javaone > _______________________________________________ > Jython-users mailing list > Jyt...@li... > https://lists.sourceforge.net/lists/listinfo/jython-users > |