Difference between revisions of "Dictionary"

From CS 61A Wiki
Jump to: navigation, search
[checked revision][checked revision]
(add content)
m (Iteration techniques: reword)
Line 75: Line 75:
 
</syntaxhighlight>
 
</syntaxhighlight>
  
To iterate over the key-value pairs of a dictionary, use:
+
To iterate over the (key, value) pairs of a dictionary, use:
 
<syntaxhighlight lang="python">
 
<syntaxhighlight lang="python">
 
for key, value in d.items():
 
for key, value in d.items():

Revision as of 22:27, 3 June 2014

A dictionary is an unordered collection of key-value pairs. The keys of a dictionary must be unique and immutable.

Creation

A dictionary is created by enclosing comma-separated key: value mappings in braces:

dict = {key0: val0, key1: val1}
An empty dictionary is constructed with {}.

Alternatively, a dictionary can be constructed by dict(s), for a sequence s of key-value pairs. Example:

>>> dict([(1, 1), (2, 4), (3, 9)])
{1: 1, 2: 4, 3: 9}

Length

The number of key-value pairs in dictionary d is given by len(d).

Addition

A key-value pair is added to dictionary d by d[key] = value. Example:

>>> d = {1: 1, 2: 4, 3: 9}
>>> d[4] = 16
>>> d
{1: 1, 2: 4, 3: 9, 4: 16}

If key already exists in d, the existing value is overwritten with value.

Deletion

To delete a key-value pair, use del d[key]. Example:

>>> d = {1: 1, 2: 4, 3: 9}
>>> del d[1]
>>> d
{2: 4, 3: 9}

Retrieval

To retrieve the value associated with key k, use d[k]. Example:

>>> d = {1: 1, 2: 4, 3: 9}
>>> d[2]
4

Key membership test

To test if key k is a key in the dictionary, use k in d. Example:

>>> d = {1: 1, 2: 4, 3: 9}
>>> 3 in d
True

Iterators

There are several dictionary methods that return iterators over parts of a dictionary. For dictionary d:

  • d.keys() returns an iterator over the keys.
  • d.values() returns an iterator over the values.
  • d.items() returns an iterator over the (key, value) pairs.

Example:

>>> d = {1: 1, 2: 4, 3: 9}
>>> d.keys()
dict_keys([1, 2, 3])
>>> d.values()
dict_values([1, 4, 9])
>>> d.items()
dict_items([(1, 1), (2, 4), (3, 9)])

Iteration techniques

To iterate over the keys of a dictionary use:

for key in d:
    ...

To iterate over the (key, value) pairs of a dictionary, use:

for key, value in d.items():
    ...

To iterate over the values of a dictionary, use:

for value in d.values():
    ...

Sources