How to convert python dict object to equivalent Java object?

I need to convert python code to equivalent Java code. Python makes life easier for developers by providing many shortcuts. But now I need to port the same thing to Java. I was wondering what would be the equivalent of dict objects in java? I tried using HashMap, but life is hell. First, consider this,

# Nodes is a dictionary -> Key : (Name, Strength) for node, (name, strength) in nodes.items(): nodes[node] = (name, new_strength) 

So how do you translate this into Java? To start, I used the HashMap object, so

 Map<Integer, List> nodesMap = new HashMap<Integer,List>(); /* For iterating over the map */ Iterator updateNodeStrengthIterator = nodesMap.entrySet().iterator(); while(updateNodeStrengthIterator.hasNext()){ } 

My problem is getting the List part, which contains the name and strength, and then updating the Strength part. Is there any way to do this? Should I consider some other data structure? Please, help.

+6
java python dictionary hashmap
source share
3 answers

Probably the easiest way to create a class for a tuple is (Name, Strength):

 class NameStrength { public String name; public String strength; } 

Add getters, setters, and constructor, if necessary.

Then you can use the new class on your map:

 Map<Integer, NameStrength> nodesMap = new HashMap<Integer, NameStrength>(); 

In Java 5 and above, you can repeat like this:

 for (NameStrength nameStrength : nodesMap.values()) {} 

or like this:

 for (Entry<Integer, NameStrength> entry : nodesMap.entrySet()) {} 
+4
source share

well always jython . here a little from this article which offers a nice side by side with python / java view

Jython's analogs for Java class collections are much more tightly integrated into the kernel language, allowing more concise descriptions and useful functions. For example, note the difference between Java code:

 map = new HashMap(); map.put("one",new Integer(1)); map.put("two",new Integer(2)); map.put("three",new Integer(3)); System.out.println(map.get("one")); list = new LinkedList(); list.add(new Integer(1)); list.add(new Integer(2)); list.add(new Integer(3)); 

and Jython code:

 map = {"one":1,"two":2,"three":3} print map ["one"] list = [1, 2, 3] 

edit: what's wrong, just using put () to replace the values?

 map.put(key,new_value); 

here is a small sample program:

 static public void main(String[] args){ HashMap<String,Integer> map = new HashMap<String,Integer>(); //name, age map.put("billy", 21); map.put("bobby", 19); year(map); for(String i: map.keySet()){ System.out.println(i+ " " + map.get(i).toString()); } } // a year has passed static void year(HashMap<String,Integer> m){ for(String k: m.keySet()){ m.put(k, m.get(k)+1); } } 
+2
source share

Java does not have the equivalent of an embedded tuple. You will need to create a class that combines the two to mimic it.

+1
source share

All Articles