jpype-project / jpype

JPype is cross language bridge to allow Python programs full access to Java class libraries.
http://www.jpype.org
Apache License 2.0
1.12k stars 181 forks source link

Convert HashMap to dict #968

Closed chanshing closed 3 years ago

chanshing commented 3 years ago

First off, thanks for the awesome package.

I have a static Java method that returns a HashMap<String, String> instance. I want to know if there's a simpler way to convert it to a dict that I may be missing:

hashmap_result = jpype.JClass('MyClass').methodThatReturnsHashMap(x)
result = dict(hashmap_result)  # doesn't work!
result = {k: hashmap_result[k] for k in hashmap_result}  # works OK
Thrameos commented 3 years ago

Hmm. It appears to work for me...

import jpype
import jpype.imports
jpype.startJVM()
import java
hm = java.util.HashMap()
hm.put("A","1")
hm.put("B","2")
u = dict(hm)
print(hm) #  Prints the Java hash map
print(u)    #  Prints a Python dict with same contents