Associative array/Iteration
Associative array/Iteration
You are encouraged to solve this task according to the task description, using any language you may know.
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
}
- iterating over key-value pairs:
for key, value in myDict.items():
print "key = %s, value = %s" % (key, value)
- iterating over keys:
for key in myDict:
print "key = %s" % key
- (is a shortcut for:)
for key in myDict.keys():
print "key = %s" % key
- iterating over values:
for value in myDict.values():
print "value = %s" % value</lang>