简体   繁体   English

py4j:dict至JAVA地图

[英]py4j: dict to JAVA map

I'm currently working on accessing HBase using python3. 我目前正在使用python3访问HBase。 The way I'm doing is using py4j to call JAVA APIs that I'm writing to access HBase. 我正在做的方式是使用py4j调用我编写的Java API来访问HBase。

I've a question related to creating a Put object which takes a qualifier and value. 我有一个有关创建带有限定符和值的Put对象的问题。

I want to pass a dictionary to a JAVA class which expects a hashmap. 我想将字典传递给需要哈希图的JAVA类。 Is it possible through py4j. 是否可以通过py4j。

I don't want to call Put for every column qualifier iteratively. 我不想为每个列限定符迭代地调用Put。 I want to pass the dict to py4j and it should be received as HashMap on JAVA side. 我想将字典传递给py4j,它应该在JAVA端作为HashMap接收。

Could you please some hints/pointers to how can this be done... 您能给我一些提示/指针如何做到这一点吗?

There are two ways to do what you want: 有两种方法可以做您想要的事情:

  1. You can create a java.util.HashMap() and use it as a dict on the python side. 您可以创建一个java.util.HashMap()并将其用作 python上的dict This is good if you pass the dictionary a lot, but you do not modify it often on the python side. 如果您通过了很多字典,这很好,但是您不经常在python一侧修改它。 This is also good if the dictionary is modified on the java side and you want to see the modifications on the python side. 如果在Java方面对字典进行了修改,并且您希望在python方面看到所做的修改,那么这也很好。
  2. Py4J can automatically convert a python dict to a HashMap when calling a Java method. 当调用Java方法时,Py4J可以自动将python字典转换为HashMap Note that the dictionary will be copied and that any change performed on the Java side won't be reflected on the Python side. 请注意,该字典将被复制,并且在Java方面执行的任何更改都不会反映在Python方面。

The easiest solution would be #1 I believe: 我认为最简单的解决方案是#1:

>>> m = gateway.jvm.java.util.HashMap()
>>> m["a"] = 0
>>> m.put("b",1)
>>> m
{u'a': 0, u'b': 1}
>>> u"b" in m
True
>>> del(m["a"])
>>> m
{u'b': 1}
>>> m["c"] = 2 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM