Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.

  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint

Tuples

Tuples are a type of sequence, like strings. But unlike strings, which can contain only characters, tuples can contain elements of any type. A tuple is an immutable object that cannot be changed once it is created. As with every sequence, tuple indices are zero based; the first element is at index 0, and the last element is at index -1.

The following program demonstrates how a tuple is defined and how its elements are accessed and displayed:

tup1.py
names=('John', 'Kelly', 'Caroline', 'Steve', 'Katheline')
print ("The names in the tuple are:", names)
print ("The first name in the tuple is", names[0])
print ("The last name in the tuple is", names[len(names)-1])
print ("The names in the tuple are")
for n in names:
   print (n)
Output:
The names in the tuple are: ('John', 'Kelly', 'Caroline', 'Steve', 'Katheline')
The first name in the tuple is John
The last name in the tuple is Katheline
The names in the tuple are
John
Kelly
Caroline
Steve
Katheline


					  

In this program, a tuple names is defined that contains five elements: John, Kelly, Caroline, Steve, and Katheline. All the elements of the tuple are displayed, followed by the first and last elements. The program also shows how elements of a tuple are accessed using the membership in operator.

The next program demonstrates searching for an element in a tuple and concatenating two tuples.

tup2.py
names=('John', 'Kelly', 'Caroline', 'Steve', 'Katheline')
n=input("Enter the name to search: ")
if n in names:
  print ("The name", n, "is present in the tuple")
else:
  print ("The name", n, "does not exist in the tuple")
countries=('U.S.', 'U.K', 'India')
names+=countries
print ("The tuples are concatenated. The concatenated tuple is", names)
Output:
Enter the name to search: Beth
The name Beth does not exist in the tuple
The tuples are concatenated. The concatenated tuple is ('John',  'Kelly',  'Caroline',
'Steve', 'Katheline', 'U.S.', 'U.K', 'India')


					  

Here, names is defined as consisting of five elements. The user is asked to enter a name to search for. Using the membership in operator, the name entered is searched for in the names tuple, and a message is displayed. Also, one more tuple, countries, is defined to include three elements. The elements in countries are added to the names tuple. The elements in the concatenated tuple, names, are then displayed.

Mappings are mutable objects that are used for mapping values to objects. The standard mapping type that we discuss next is the dictionary.

Dictionary

A dictionary is a combination of key/value pairs in which every key has to be unique. Key/value pairs are separated by a colon, and the pairs are separated by commas. The key/value pairs are enclosed in a curly brackets.

Syntax:
d = {key1 : value1, key2 : value2 }

Dictionaries are mutable, which means a dictionary can be modified, and you don’t have to create a copy of it to modify it. Dictionary keys are case sensitive and immutable because Python associates them with a unique number called a hash. Also, dictionary keys can be of mixed data types: strings, integers, and others. Table 3.5 shows some of the methods that can be applied to the dictionary.

Table 3.5. Dictionary Methods
MethodDescription
clear()Removes all items from the dictionary.
pop(key, [default])Returns and removes the value associated with the specified key from the dictionary. If the key does not exist, the method returns the default value provided. If the key does not exist and no default value is provided, a KeyError exception is raised.
update(new, [key=value...])Merges the new key/value pairs in the dictionary. The existing key/value pairs are updated.
copy()Makes a copy of the dictionary. The objects in the new dictionary are references to the objects in the original dictionary.
get(key, [default])Returns the value associated with the given key. If key is not present and default is provided, the method returns the default value. If key is not present and no default is provided, a KeyError exception is raised.
items()Returns all the items in the dictionary as a sequence of key/value tuples.
keys()Returns all the keys in the dictionary as a sequence of keys.
values()Returns all the values from the dictionary as a sequence.


The following program demonstrates how to fetch a value from the dictionary by supplying a key. Also, the program shows how to add a key/value pair to an existing dictionary and delete an existing key/value pair. The program demonstrates the use of the dictionary in accessing the capital of the country whose name is entered by the user.

dict1.py
countrycap={'U.S.' : 'Washington D.C.', 'U.K.' : 'London', 'India' : 'New Delhi', }
n=input('Enter country: ')
if n in countrycap:
   print ('The capital of', n , 'is', countrycap[n])
else:
   print ('Sorry the country', n, 'does not exist in our dictionary')
countrycap['Australia']='Sweden'
print ('The dictionary after adding a country:')
for country, capital in countrycap.items():
   print ('Capital of', country, 'is' , capital)
m=input('Enter the country to delete:')
del countrycap[m]
print ('The dictionary after deleting a country:')
for country, capital in countrycap.items():
   print ('Capital of', country, 'is' , capital)

Output:
Enter country: U.S.
The capital of U.S is Washington D.C.
The dictionary after adding a country:
Capital of U.S. is Washington D.C.
Capital of Australia is Sweden
Capital of India is New Delhi
Capital of U.K. is London
Enter the country to delete: U.K.
The dictionary after deleting a country:
Capital of U.S. is Washington D.C.
Capital of Australia is Sweden
Capital of India is New Delhi


					  

This program defines a dictionary named countrycap with three key/value pairs in it. The keys are the country names U.S., U.K., and India, and the values of these keys are the respective capitals of the countries. You ask the user to enter the country name whose capital is required. Taking the entered country name as the key, its respective value is accessed and displayed. One key/value pair is added to the dictionary, with Australia as its key and Sweden as its value. The program also displays the dictionary elements, each country with its respective capital. The program also deletes the desired country/capital pair from the dictionary.

The following program demonstrates the use of items(), keys(), values(), and get() methods of the dictionary. Also, it shows how two dictionaries are merged.

dictexample.py
student1={'John' : 60, 'Kelly' : 70, 'Caroline' : 80}
student2=dict([('David', 90), ('John',55)])
print ('The items in dictionary student1 are:', student1.items())
print ('The keys in student1 dictionary are:', student1.keys())
print ('The values in student1 dictionary are:', student1.values())
student1.update(student2)
print ('The items in dictionary student1 after merging with student2 dictionary are:',
student1.items())
n=input('Enter name whose marks you want to see: ')
if n in student1:
   print ('The marks of', n , 'are' , student1.get(n))
else:
   print ('Sorry the name', n, 'does not exist in student1 dictionary')
Output:
The items in dictionary student1 are: dict_items([('Kelly', 70), ('John', 60),
('Caroline', 80)])
The keys in student1 dictionary are: dict_keys(['Kelly', 'John', 'Caroline'])
The values in student1 dictionary are: dict_values([70, 60, 80])
The items in dictionary student1 after merging with student2 dictionary are: dict_items
([('Kelly', 70), ('John', 55), ('Caroline', 80), ('David', 90)])
Enter name whose marks you want to see: Caroline
The marks of Caroline are 80


					  

The program defines two dictionaries, student1 and student2. The student2 dictionary is created by applying the dict() function to the pairs of values. All the key/value pairs of the student1 dictionary are displayed using the items() function. Also, the keys and values of the student1 dictionary are accessed through the keys() and values() functions and displayed. The key/value pairs of the dictionary student2 are merged with the dictionary student1. While merging, the values of the keys in dictionary student1 will be updated with the values of the matching keys in dictionary student2. The merged key/value pairs are displayed. Also, the user is asked to enter a student’s name whose marks are required. Using the get() function, the supplied name is accessed and displayed.

Let’s finish the chapter by discussing one more container object, sets.

  • Safari Books Online
  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint