4 Dictionaries and sets

 

Dictionaries (http://mng.bz/5aAz), or dicts, are one of Python’s most powerful and important data structures. You may recognize them from other programming languages, in which they can be known as “hashes,” “associative arrays,” “hash maps,” or “hash tables.”

In a dict, we don’t enter individual elements, as in a list or tuple. Rather, we enter pairs of data, with the first item known as the key and the second item known as the value. Whereas the index in a string, list, or tuple is always an integer, and always starts with 0, dict keys can come from a wide variety of Python types--typically integers or strings.

This seemingly small difference, that we can use arbitrary keys to locate our values, rather than using integer indexes, is actually crucial. Many programming tasks involve name-value pairs--such as usernames/user IDs, IP addresses/hostnames, and email addresses/encrypted passwords. Moreover, much of the Python language itself is implemented using dicts. So knowing how dicts work, and how to better use them, will give you insights into the actual implementation of Python.

I use dicts in three main ways:

Hashing and dicts

Sets

Exercise 14 Restaurant

Working it out

Solution

Screencast solution

Beyond the exercise

Exercise 15 Rainfall

Working it out

Solution

Screencast solution

Beyond the exercise

Exercise 16 Dictdiff

Working it out

Solution

Screencast solution

Beyond the exercise

Exercise 17 How many different numbers?

Working it out

Solution

Screencast solution

Beyond the exercise

Summary

sitemap