Associative array/Iteration

From Rosetta Code
Revision as of 02:29, 3 August 2009 by rosettacode>Spoon! (started task with java and python)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Task
Associative array/Iteration
You are encouraged to solve this task according to the task description, using any language you may know.

Show how to iterate over the key-value pairs of an associative array, and print each pair out. Also show how to iterate just over the keys, or the values, if there is a separate way to do that in your language.

Java

<lang java>Map<K, V> myDict; // initialize and add items to myDict

// iterating over key-value pairs: for (Map.Entry<K, V> e : myDict.entrySet()) {

   K key = e.getKey();
   V value = e.getValue();
   System.out.println("key = " + key + ", value = " + value);

}

// iterating over keys: for (K key : myDict.keySet()) {

   System.out.println("key = " + key);

}

// iterating over values: for (V value : myDict.values()) {

   System.out.println("value = " + value);

}</lang>

Python

<lang python> myDict = { # list items here

        }
  1. iterating over key-value pairs:

for key, value in myDict.items():

   print "key = %s, value = %s" % (key, value)
  1. iterating over keys:

for key in myDict:

   print "key = %s" % key
  1. (is a shortcut for:)

for key in myDict.keys():

   print "key = %s" % key
  1. iterating over values:

for value in myDict.values():

   print "value = %s" % value</lang>