Sign InCoursewareNuggetsTutorials CoursesCodePad

Python Dictionaries

Andrew's shopping list, as shown in the next example, is quite short. If he wants to know how many tomatoes to buy, he can simply skim through the list and find that the answer is 4. To simulate this task with a Python program, we would need a long if-else statement as follows.

shopping = ["apple", 3, "cheese", 1, "tomato", 4, "egg", 12] item = input("Please enter the item's name:") if item == "apple": print "The amount to buy is", shopping[1] elif item == "cheese": print "The amount to buy is", shopping[3] elif item == "tomato": print "The amount to buy is", shopping[5] elif item == "egg": print "The amount to buy is", shopping[7] else: print "The item is not found."

What if we want to look up something from a large collection with thousands of items?

Introducing Dictionaries

In many cases, it may not be appropriate to organize a collection of data sequentially by an integer index, such as lists or tuples. A different kind of data collection, called a map, is very good at supporting quick lookup tasks. In a map, each item has a key and a corresponding value. Therefore, we sometimes call these elements key-value pairs.

In Python, a built-in map implementation is provided by the dictionary data type. The mapping is from a key to a value. The keys can be any immutable types, such as strings, numerical types, and tuples. The values can be any types.

Accessing Dictionary Items

Unlike lists, dictionaries are unordered. Therefore, it does not matter in what order the key-value pairs are entered in a dictionary. For example, shopping and tobuy are the same dictionary, even though their elements are not in the same order.

shopping = {"apple": 3, "cheese": 1, "tomato": 4, "egg": 12} tobuy = {"cheese": 1, "egg": 12, "apple": 3, "tomato": 4} print shopping == tobuy

Elements in a Python dictionary are enclosed by braces { }. Each key and its value are separated by a colon (:). The syntax for accessing a value of a dictionary is the same as for accessing elements of sequences, except that a key, instead of an index, is used within the square brackets: shopping['apple']. Using a dictionary to store Andrew's shopping list, we can easily get the value (the amount to buy) by a given key (item name).

shopping = {"apple": 3, "cheese": 1, "tomato": 4, "egg": 12} print "The amount of apple is", shopping["apple"] print "The amount of cheese is", shopping["cheese"] print "The amount tomoto is", shopping["tomato"] print "The amount egg is", shopping["egg"]
© CS Wonders·About·Gallery·Fun Facts·Cheatsheet