Python Fundamentals – Dictionaries

Python Fundamentals – Dictionaries

INTRODUCTION

A dictionary is like an address-book where you can find the address or contact details of a person by knowing only his/her name, i.e., we associate keys (name) with values (details). Note that the key must be unique just like you cannot find out the correct information if you have two persons with the exact same name.
A dictionary is a very flexible object for storing various kind of information. A list is a collection of objects indexed by an integer going from 0 to the number of elements minus one. Instead of looking up an ele­ment through an integer index, it can be more handy to use a text. Roughly speaking, a list where the index can be a text is called a dictionary in Python. In other words, a dictionary is:

  • An associative array.
  • A mapping from keys to values.
  • A container (collection) that holds key:value pairs.

CONCEPT OF KEY:VALUE PAIR

Python’s dictionary (its keyword is diet) is a data type that stores multiple data items (elements) of different types. A dic­tionary is like a list, but more general. In a list, the indices have to be integers; in a dictionary they can be (almost) any type.
You can think of a dictionary as a mapping between a set of indices (which are called keys) and a set of values. Each key maps to a value. The association of a key and a value is called a keyrvalue pair or sometimes an item. Pairs of keys and values are specified in a dictionary by using the notation:

Notice that the key rvalue pairs are separated by a colon and the pairs are separated themselves by commas and all this is enclosed in a pair of curly braces. For example, here is an empty dictionary and several dictionaries containing key:value pairs:

Note that a comma after the last pair is optional.
Python doesn’t store dictionary elements in any particular order. If you enter elements in one order, they may be stored in another (essentially random) order inside Python. The order of the key:value pairs is not the same. In fact, if you type the same example on your computer, you might get a different result. In general, the order of items in a dic­tionary is unpredictable. But that’s not a problem because the elements of a dictionary are never indexed with integer indices. Instead, you use the keys to look up the corresponding values. For example,

Characteristics of a Dictionary

  • A dictionary is an unordered collection of objects.
  • Values are accessed using a key.
  • A dictionary can shrink or grow as needed.
  • The contents of dictionaries can be modified.
  • Dictionaries can be nested.
  • Sequence operations, such as slice cannot be used with dictionaries.

CREATION, INITIALIZATION AND ACCESSING THE ELEMENTS IN A DICTIONARY

A collection that allows us to look up information associated with arbitrary keys is called a mapping. Python dictionaries are mappings. Some other programming lan­guages provide similar structures called hashes or associative arrays. A dictionary can be created in Python by listing key:value pairs inside of curly braces. Here is a simple dictionary that stores some usernames and passwords.

Notice that keys and values are joined with a and commas are used to separate the pairs. The main use for a dictionary is to look up the value associated with a particular key. This is done through indexing notation. More than one entry per key not allowed, which means no duplicate key is allowed.
An empty dictionary (without any items) is written with just two curly braces, like this: {}.

To add an item to the dictionary (empty string), we can use square brackets ([ ]) for accessing and initializing dictionary values. For example,

To access dictionary elements, you use the familiar square brackets along with the key to obtain its value:

Dictionary dictl is empty while dict2 has two data items. The keys in dict2 are ‘name’ and ‘deptcode’, and their associated value items are ‘Raj’ and 7, respectively. Access to the value is through the key, as you can see from the explicit access to the ‘name’ key.
If we attempt to access a data item with a key which is not part of the dictionary, we get an error:

In this example, we tried to access a value with the key ‘salary’ which, as you know, does not exist from the code above. The best way to check if a dictionary has a specific key is to use the dictionary’s has_key() method. The Boolean hasjkeyf) method will return a 1 if a dictionary has that key and 0 otherwise.

Once the has_key() method has return 1, meaning that a key exists, then you can access it without having to worry about getting the KeyError.
Let us take a look at another dictionary example, using keys other than strings:

Rather than adding each key:value pair individually, we could have also entered all the data for dict3 at the same time:

Creating the dictionary with a set key:value pair can be accomplished if all the data items are known in advance. The goal of the examples using dict3 is to illustrate the variety of keys that you can use.

Example 1
Program to enter name and percentage marks in a dictionary and then display informa¬tion on the screen.

Figure 17.1 Program for Example 1

Example 2
Program to enter name and percentage marks in a dictionary and then display informa¬tion in sorted order according to percentage marks.

Figure 17.2 Program for Example 2

How to Update Dictionaries?
You can update a dictionary by adding a new entry or element (i.e., a key:value pair), modifying an existing entry, or deleting an existing entry.

If the key does exist, then its previous value will be overridden by its new value. You may also add the contents of an entire dictionary to another dictionary by using the update() built-in method.

How to Remove Dictionary Elements and Dictionaries?
You can remove item from the existing dictionary by using del statement. You either remove individual dictionary elements or clear the entire contents of a dictionary. However, if you really want to “remove” an entire dictionary, use the del statement. Here are some deletion examples for dictionaries and dictionary elements:

DICTIONARY FUNCTIONS AND METHODS

Just like the other built-in types, dictionaries have methods and functions.

dict()
The dict() constructor builds dictionaries directly from lists of key:value pairs stored as tuples. When the pairs form a pattern, list comprehensions can compactly specify the key:value list.

Because dict() is the name of a built-in function, you should avoid using it as a variable name. You can create a dictionary during run time using dict(), also called dynamic allocation.

cmp()
This is used to check whether the given dictionaries are same or not. If both are same, it will return 0, otherwise return 1 or -1. If the first dictionary having more number of items, then it will return 1, otherwise return -1.

len()
The len() built-in function gives us the number of items in a dictionary, i.e., it returns the number of key:value pairs:

clear()
The clear() method removes all items from the dictionary.

get()
The get() method is an easy way to get a value from a dictionary. Ordinarily, when you try to access an item that is not present in the dictionary, things go very wrong:

But when you use get() function it displays None:

As you can see, when you use get to access a non-existent key, there is no exception. Instead, you get the value None. You may supply your own “default” value, which is then used instead of None:

has_key()
The has_key() method checks whether a dictionary has a given key. The expression d.has_key(k) is equivalent to k in d.

pop()
The pop() method can be used to get the value corresponding to a given key, and then remove the key:value pair from the dictionary:

popitem()
The popitem() method is similar to list.pop, which pops off the last element of a list. Unlike list.pop, however, popitem pops off an arbitrary item because dictionaries don’t have a “last element” or any order whatsoever. This may be very useful if you want to remove and process the items one-by-one in an efficient way (without retrieving a list of the keys first):

Although popitem is similar to the list method pop, there is no dictionary equivalent of append (which adds an element to the end of a list). Because dictionaries have no order, such a method wouldn’t make any sense.

keys()
The keys and values can be extracted as lists from a dictionary. The keys() method of a dictionary object returns a list of all the keys used in the dictionary, in arbitrary order.

values()
The values() method returns list of values.

items()
Returns a list of tuples (key,value) representing the key:value pairs. These are useful for when you wish to iterate through a dictionary’s keys or values, even though in no par¬ticular order.

Example 3
Program that converts dictionary to list.

Figure 17.3 Program for Example 3

SOLVED EXERCISE

Question 1.
What is dictionary?

Answer:
A dictionary is mutable and is another container type that can store any number of Python objects, including other container types. Dictionaries consist of pairs (called items) of keys and their corresponding values. Python dictionaries are also known as associative arrays or hash tables.

Question 2.
Compare and contrast dictionaries (diets) with other Python data types.

Answer:
(a) Dictionaries are a container type that stores data, like lists and tuples.
(b) Dictionaries are a mapping data type indexed by keys.
(c) A dictionary’s elements (the items it contains) are key:value pairs. In contrast, lists and tuples store data by using numeric indexes (they are sequence data types) and support indexing and slicing.
(d) Dictionaries are mutable. That means a dictionary can be modified in place you don’t have to create a copy of it to modify it (as you do with strings and tuples). However, a diet’s keys must be immutable.

Question 3.
What are the advantages of hash?

Answer:
Hashes are used for space-efficient storage, for security and cryptography, and so on. Another benefit of hashing is that after the hash is computed, keys can be looked up directly, there’s no need for the computer to search through a whole list of keys. In Python, this feature makes dictionaries very fast.

Question 4.
Can Python store dictionary elements in any particular order?

Answer:
Python doesn’t store dictionary elements in any particular order. If you enter ele¬ments in one order, they may be stored in another (essentially random) order inside Python. For example,

Question 5.
What is a mapping?

Answer:
A mapping is a structure in which values are stored and retrieved according to a key. This is often called a dictionary, because it behaves similarly to a common dictionary.

Question 6.
What is the another name for a mapping?

Answer:
A dictionary.

Question 7.
What are the characteristics of a Python dictionary?

Answer:
Characteristics of a Python dictionary are as follows:
(a) A dictionary is an unordered collection of objects.
(b) Values are accessed using a key rather than by using an ordinal numeric index.
(c) A dictionary can shrink or grow as needed.
(d) Dictionaries can be nested.
(e) The contents of dictionaries can be modified.

Question 8.
A dictionary is an mutable object. Comment.

Answer:
A dictionary is mutable because its existing items can be modified, new items can be added, and existing items can be deleted.

Question 9.
A dictionary is an unordered collection of objects. Comment.

Answer:
The items in a dictionary are not maintained in any specific order, and a dictionary can contain references to any type of objects.

Question 10.
Can sequence operations, such as slicing and concatenation be applied to dictio¬naries?

Answer:
No, a dictionary is not a sequence. Because it is not maintained in any specific order, operations that depend on a specific order cannot be used.

Question 11.
Write the syntax of a dictionary.

Answer:
A dictionary consists of none, one, or more key lvalue pairs, separated by commas, and enclosed in a pair of curly braces.

Question 12.
Can you remove keyivalue pairs from a dictionary, and if so, how?

Answer:
You can use del to remove an existing keyivalue pair from a dictionary.

Question 13.
What do you mean by traversing a dictionary?

Answer:
Traversing a dictionary means visit each element of the dictionary to display its values on the screen.

Question 14.
Can you merge two dictionaries?

Answer:
Two dictionaries can be merged in to one by using update () method. It merges the keys and values of one dictionary into another and overwrites values of the same key.

Question 15.
Write a program to traverse a dictionary and display its value on the screen in dif-ferent lines.

Answer:

Figure 1 Program for Q15

Question 16.
Write a program to traverse a dictionary and display its value on the screen in same line.

Answer:

Figure 2 Program for Q16

Question 17.
Write a program to create dictionary and display information on the screen.

Answer:

Figure 3 Program for Q17

Question 18.
Write a program to put information on the screen in ascending order of names.

Answer:

Figure 4 Program for Q18

Question 19.
Explain cmp() function of Python.

Answer:
Python built-in function cmp() accepts two values as parameters and returns -1, 0 or 1, corresponding to the relative ordering of the parameters. Thus, cmp(a,b) returns -1 if a precedes b, 0 if they are the same, and 1 if a follows b.

Question 20.
What does the keys(), valuesQ and items() function do?

Answer:
keys(): Returns a list of the keys.
values(): Returns a list of the values.
items(): Returns a list of tuples (key,value) representing the key:value pairs.

Question 21.
Write a program to create students details and then delete particular roll no using name.

Answer:

Figure 5 Program for Q21

Question 22.
Write different capabilities of dictionary.

Answer:
A dictionary has the following capabilities:
(a) Ability to iterate over keys or values or keyvalue pairs.
(b) Ability to add keyvalue pairs dynamically.
(c) Ability to lookup a value by key.

Question 23.
Find the output of the following programs:

Answer:
(a) 2
(b) [‘publisher’, ‘price’, ‘title’] (c) [‘BPB’, ’99’, ‘Computer Science’] (d) [(‘publisher’: ‘BPB’), (‘price’: 99), (title’: ‘Computer Science’)] (e) {}
(f) -1
-1
1
0

Multiple choice questions

Question 1.
The association of a key and a value is called:
(a) A key-value pair
(b) An item
(c) Both (a) and (b)
(d) All of the above

Answer:
(c)

Question 2.
Dictionary are represented using:
(a) {}
(b) [] (c) ()
(d) None of the above

Answer:
(a)

Question 3.
In general, the order of items in a dictionary is:
(a) Unpredictable
(b) Predictable
(c) known
(d) None of these

Answer:
(a)

Question 4.
If the dictionary lengths are different, then for cmp(dict1, dict2), cmp() will return___number if dictl is longer:
(a) Positive number
(b) Negative number
(c) Zero
(d) All of the above

Answer:
(a)

Question 5.
The dictionaries have the same length, same keys, and same values for each key, then the dictionaries are an exact match and returns:
(a) 1
(b) -1
(c) 0
(d) None of these

Answer:
(c)

About the author

James Palmer

Leave a Comment