Python's dictionary (its keyword is diet) is a data type that stores multiple data items (elements) of different types. In a dictionary, each element is associated with a unique key, which is a value of any immutable type. When you use a dict, you use the key to return the element associated with the key.

You use a dictionary when you want to store and retrieve items by using a key that doesn't change and when you don't care in what order Python stores the items. (In dictionaries, elements aren't numbered.)

Tip Here's what a Python dictionary is not: A Python dictionary bears only a small resemblance to the kind of dictionary that contains words and their definitions. In Python, a dictionary is more like a list of employees and their employee numbers. Because each employee number is unique, you can look up that employee by typing his or her number.

REMEMBER Dictionaries are mutable, like lists, but their keys are immutable. Here is an example of a dictionary with two key:value pairs:

swallow_velocity = {"european": "47", "african": "69"}

You can find out much more about using dictionaries in Chapter 9. Sets

A set stores multiple items, which can be of different types, but each item in a set must be unique. You can use Python sets to find unions, intersections, differences, and so on—just like the sets that probably annoyed you in school.

One use for sets is when you have repetitious data and you want to ignore the repetition. For example, imagine that you have an address database and you want to find out which cities are represented, but you don't need to know how many times each city appears in the database. A set will list each city in the database only once.

The syntax for a set is a little different from the syntax of the other data types described in this section. You use the word set followed by a name (or a group of elements) in parentheses. Here is a set that finds each unique element in a list. You'll notice that the elements are out of order in the set. That's because Python doesn't store set elements in alphanumeric order (the same is true for dicts):

>>> mylist = ['spam', 'lovely', 'spam', 'glorious', 'spam'] >>> set(mylist)

Was this article helpful?

0 0

Post a comment