LearnWave
Learn it. Master it.

Tuples and Dictionaries

Dictionary operations and methods

Traverse a dictionary and use its methods.

Membership with in and not in checks the keys: for marks = {'Asha': 91, 'Ravi': 78}, 'Asha' in marks is True, but 91 in marks is False (91 is a value, not a key).

Traversing a dictionary:

  • for key in marks: print(key, ':', marks[key])
  • for key, value in marks.items(): print(key, ':', value)

Useful functions and methods:

  • len(): the number of items.
  • dict(): makes a dictionary, for example from a list of key-value pairs.
  • keys(), values(), items(): views of the keys, the values, and the (key, value) pairs.
  • get(key): the value for key, or None if the key is absent. It is the safe way to look up, because it never gives a KeyError: marks.get('Kiran') gives None.
  • update(dict2): adds the items of dict2 (changing values for keys already present).
  • del marks[key] deletes one item; del marks deletes the whole dictionary; clear() removes all the items, leaving an empty dictionary {}.

With these, programs can count, look up and update data by a name or a number.

get() is the safe way to look up.

Practise this lesson

Questions that get harder as you improve, a Tutor that helps without giving the answer away, and progress you can see. Free for every learner.

No account, no email address. Opens the real product.