Collections: Dictionaries or Maps

 

Python

Java

 

A dictionary is a mutable collection of 0 or more unique key/value pairs.  Put another way, a dictionary contains a set of keys, where each key is associated with a value.

 

The len function returns the number of elements in a dictionary.

 

The subscript operator accesses a value at an existing key.  This operator also can be used to a add a new key or to replace a value at an existing key.

 

The dict class includes many useful methods.

 

 

 

 

 

Example:

 

# Associate 10 random ages between 1 and 10

# with consecutive names

names = {}

for i in range(1, 11):

    name = "Name" + str(i)

    names[name] = random.randint(1, 10)

 

// Print all keys and their values

for key in names.keys():

    print(key, names[key])

 

 

 

A map is a mutable collection of 0 or more unique key/value pairs.  Put another way, a map contains a set of keys, where each key is associated with a value.  A generic map constrains its keys to the same supertype and values to the same supertype.

 

The Map interface includes the methods common to all implementing classes.  The SortedMap interface extends the Map interface to include methods for sorted maps. 

 

The implementing classes include HashMap and TreeMap.  A TreeMap can return its keys in sorted order.  Thus, it also implements the SortedMap interface.

 

A generic map specifies the key/value types of the map variable and the instantiated map object, as follows:

 

Map<String, Integer> names = new HashMap<String, Integer>();

SortedMap<Integer, Integer> ints = new TreeMap<Integer, Integer>();

 

Example:

 

// Associate 10 random ages between 1 and 10

// with consecutive names

for (int i = 1; i <= 10; i++){

    String name = "Name" + i;

    names.put(name, (int)(Math.random() * 10 + 1));

 

// Print all keys and their values

for (String key : names.keySet())

    System.out.println(key + " " + names.get(key));

 

Note the use of a for loop to access the set of keys returned by keySet().

 

Previous

Index

Next