Loading...

Java vs. Python : Why I Heart Python

January 25, 2008 3 Comments Tagged as: flame-bait java python

I've been working in a Java environment recently. I've found that no matter how much Java I think I knew in school, it must not have stuck with me. I'm having to relearn data structures in Java, and now that I know a thing or two, I've come to realize that Java's data structures are hugely verbose and rather difficult to work with sometimes. Of course, this is because I've been spoiled recently working in more "fun" languages, like my python...

Consider the following situation. I had two maps that needed to be compared. If you're not a Java guy, think key->value structure. Anyway, I solved the problem by creating a Set (think array) or all the keys that were different between the two, and then showing the results. Here's the java result:

    Set<String> changes = null;
        Iterator it = map1.keySet().iterator();
        while(it.hasNext()) {
                String key = (String)it.next();
                if(map2.containsKey(key)) {
                        if(!map1.get(key).equals(map2.get(key))) {
                                changes.add(key);
                        }
                } else {
                        changes.add(key);
                }
        }                

In python, I just do this:

changes = []
for key in dict1.keys():
    if key in dict2:
        if dict1[key] != dict2[key]:
            changes.append(key)
    else:
        changes.append(key)

Now, I may be nit-picking, but you tell me which one is more clear and concise. Sometimes, being verbose isn't such a good thing after all... (I'm thinking of a specific person who talks way too much)

Comments on "Java vs. Python : Why I Heart Python"

On February 21, 2008 @ 04:02 srstanic said...
In Java you can also try this:

Set<String> changes = null;
  for (String key : map1.keySet())
  {
    if(map2.containsKey(key)) {
      if(!map1.get(key).equals(map2.get(key))) {
        changes.add(key);
      }
    } else {
      changes.add(key);
    }
  }

          
On February 21, 2008 @ 15:02 Paul Hummer said...
Ah, much closer to a syntax that makes me feel all warm and fuzzy!  :)  I've found lots of books that are "Python for Java Programmers" but there should be a "Java for Python Programmers" book.
          
On February 27, 2008 @ 05:02 sharmila said...
set1 = set(dict1.iteritems())

set2 = set(dict1.iteritems())

diff = set1 - set2

diff_keys  = [key for (key, value) in diff]

This is another way of achieving the same in ptyhon
          

Leave a Comment