Free Online Courses for Software Developers - MrBool
× Please, log in to give us a feedback. Click here to login
×

You must be logged to download. Click here to login

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

Introduction to Dictionaries and Tuples in Python

In this tutorial, we will about the dictionary data type of Python, how this data type is different from other sequence data structure like list or arrays. We also learned about Tuples in Dictionary.

Introduction

Generally, a dictionary is a collection of words. These words are associated with a definition. If you want to find out a definition then you should know the exact word. We can call this word as “Key”.

Pythons dictionary are known as mappings. Mappings are also collection of different objects but they use keys to store an object instead of its relative index or position. Mapping simply map keys to associated values rather than maintaining any left to right order. Dictionaries have the property of mutability just as list. They can add or remove items as demand and also change their positions. Dictionaries are used mostly when a collection’s items are named or ladled, for example fields of a database record.

Mapping Operations

In Python, dictionaries are used when there is a need to create a record like data structure where values stored in it are associated with some sort of key values. This “key:value” pair is coded in curly braces. For example, consider a dictionary with three item with keys “car”, “model” and “color” then we can create a dictionary like this:

>>> D = {'car': 'BMW', 'price':5000, 'color': 'black'}

The keys of this dictionary cab be used to fetch and change the values associated with them. The dictionary index operation uses the keys instead of relative positions of the values. The syntax of these operations will be similar to the other sequence data types. For example:

Listing 1: Representing the simple index operation

>>> D['car']  	  # Fetch value of key food
'BMW'
>>> D['price'] += 1000   # Adding 1 to quantity value
>>> D
{'car': 'BMW', 'price': 6000, 'color': 'black'}

In the following example code Listing 2, we fill an empty dictionary with one key at a time. Assignments to new dictionary keys will create those keys:

Listing 2: Representing the value assignment to dictionary

>>> C = {} #
>>> C['name'] = 'Alok' # Key creation by assignment  #
>>> C['job'] = 'dev'
>>> C['age'] = 25
>>> C
{'age': 25, 'job': 'dev', 'name': 'Alok'} ##
>>> print(C['name'])

Alok

Python provides a dict type name to create dictionaries. It can be done either passing keyword arguments (name=value syntax in function calls) or zipping together sequences of keys and values obtained at runtime.

Listing 3: Representing the use of "dict" type name to create dictionary

>>> alok1 = dict(name='Alok', job='dev', age=25) 		 	## Keywords #
>>> alok1
{'age': 25, 'job': 'dev', 'name': 'Alok'} #
>>> alok2 = dict(zip(['name', 'job', 'age'], ['Alok', 'dev', 25])) 	 # Zipping#
>>> alok2    #
{'job': 'dev', 'name': 'Alok', 'age': 25}

Note down the difference in the output sequence. They are not same as we input them.

More on Nesting

As we saw in Listing 3, we created a dictionary to represent a person with three keys. Suppose, the information we want to store about this man is more complex. Now we want to store both first and last names and multiple job titles. For this, Python’s object nesting feature will be used. We can create a dictionary using nesting, coded as a literal all at once. This dictionary stores more structured information:

Listing 4: Representing the Nested Dictionary

>>> rec = {'name': {'first': 'Alok', 'last': 'Shukla'},           #name
'jobs': ['dev', 'mgr'],    #jobs 
'age': 25}    #age

In Listing 4, dictionary has again three keys “names”, “jobs” and “age”. But this time the values are more complex, with a nested dictionary having the keys “first” and “last” to support multiple name values and a nested list to store multiple job roles and future expansion. To access the elements of this dictionary, we use the dictionary keys as indexes:

Listing 5: Representing how to access the elements of nested dictionary

 >>> rec['name']  					      
{'last': 'Shukla', 'first': 'Alok'}
>>> rec['name']['last'] 				      # Index to the nested dictionary
'Shukla'
>>> rec['jobs']  					      # 'jobs' is a nested list #
['dev', 'mgr']
>>> rec['jobs'][-1]  					      # Index to the nested list
'mgr'
>>> rec['jobs'].append('janitor')  		      
>>> rec
{'age': 25, 'jobs': ['dev', 'mgr', 'janitor'], 'name': {'last': 'Shukla','first': 'Alok'}}    #rec

Now this example clearly shows the flexibility of Python. Complex information structure can be built directly and easily using nesting. If we want to create same structure in a language like C, it would be tedious and more code will have to be written. We have to define and declare structures and arrays, link them together properly and fill out the values. In Python, all of this is automatically done. This is the main benefit of using scripting languages like python. One more advantage of Python over other languages is garbage collection. In C, user has to manually manage the memory allocation but in Python, when an object lost its all references, all of the memory occupied by that object is automatically cleaned up for us.

Sorting Keys

Normally, dictionaries don’t maintain any order because they are not sequential. They don’t follow any specific left to right order as other data structure may follow. When we create a dictionary, and then print its values, it can be possible that the output values will be in different order other than in which we input them. This order may vary per Python version and other variables:

Listing 6: Representing the ordering of dictionary

>>> D = {'A': 7, 'B': 6, 'C': 5}       #D
>>> D
{'A': 7, 'C': 5, 'B': 6}

But if there is a condition when we have to maintain an order of the dictionaries items, then what shall we do? A common solution to this problem is to use dictionary keys method to grab a list of keys then sort this list with the list sort method and then use the for loop to print the output:

>>> Ks = list(D.keys()) 			 	
>>> Ks  
['A', 'B', 'C']
>>> Ks.sort() 				 # list of the sorted keys
>>> Ks
['A', 'B', 'C']
>>> for key in Ks: 				 # sorted keys are used for iteration'
print(key, '=>', D[key])  
A => 7					 # ordered output'
B => 6
C => 5	

Newer python version supports a built-in function sorted() for this purpose. This function sorts a variety of object types:

>>> D
{'a': 1, 'c': 3, 'b': 2}
>>> for key in sorted(D):       #key in sorted
    print(key, '=>', D[key])      #print
a => 1
b => 2
c => 3

As we learn from previous example, built-in methods are more useful and time saving when we talks about good programming practice.

Some Common Dictionary Operations

At last we’ll learn some simple operations on dictionaries. Python provides a del statement to remove a key: value pair from a dictionary. For example, a dictionary contains the names of the fruits and the number of each fruit in stock:

Listing 7: Simple Dictionary Operations

>>> inventory = {"apples": 430, "bananas": 312, "oranges": 525, "pears": 217}      #inventory
>>> print(inventory)     # print
{’pears’: 217, ’apples’: 430, ’oranges’: 525, ’bananas’: 312}

Suppose, if someone buys all the pears, the pears entry will be removed from the dictionary:

>>> del inventory["pears"]         #del inventory
>>> print(inventory)       #print
{’apples’: 430, ’oranges’: 525, ’bananas’: 312}

Or, if new stock of pears is about to a arrive, we can just change the value associated with the pears:

>>> inventory["pears"] = 0
>>> print(inventory)          #inventory print
{’pears’: 0, ’apples’: 430, ’oranges’: 525, ’bananas’: 312}  #apples oranges and bananas

If a new shipment of bananas has been arrived then we could do something like this to update the values in dictionaries:

>>> inventory["bananas"] += 200   #bananas inventory
>>> print(inventory)    # print inventory 
{’pears’: 0, ’apples’: 430, ’oranges’: 525, ’bananas’: 512}     #pears

We can use len() function to know the number of key: value pairs of the dictionary:

>>> len(inventory)       #Ien Inventory
4        #4

Here we learned about the dictionary data type of Python, how this data type is different from other sequence data structure like list or arrays. We learned how to create a dictionary, how to store values in it, how to use nested operations to create complex data structures. Then we learned how we can sort the dictionary elements to maintain some sort of ordering and at last we concluded this topic discussing some common operations such as deletion of items from a dictionary. Now we are ending this discussion believing that this tutorial will be helpful for anyone want to learn about Python’s dictionary.

Introduction to Tuples in Dictionary

Tuples are simple group of objects in Python. Tuples have everything similar like lists except that they cannot change their places (immutable) and usually written as a series of items in parentheses instead of square brackets. The basics of tuples are given below:

  • Tuples are ordered collection of arbitrary objects
  • The tuples strictly maintain a left to right order when storing the elements. Just like lists, tuples can store any data type.

  • Access by index value
  • Tuples are accessed by their index numbers like arrays or lists and support all offset operations such as indexing and slicing.

  • Immutable
  • Tuples are also sequence type data structure like dictionary or lists so they support many of the sequence operations. However, Tuples are immutable in nature. The in place change operations are now allowed in tuples.

  • Fixed size and Nesting capability
  • Unlike lists or dictionaries, tuples have a fixed size constraint. They can’t expand or shrink as par the demand of the operation. Tuples can store variable type of data and support nesting to create compound data structure.

Operation of Tuples

A tuple stores different data items, separated by commas, and in a sequential order. To enclose these values, we use parentheses instead of brackets. For example:

>>BMW=(“M4 GT series”, ”German”, ”Sports”,2009) 
>>BMW
('M4 GT series', 'German', 'Sports', 2009)

Tuples are just like records. They store different data items which are related with each other. As in above example code, BMW tuple stores different data types, integer and strings. No description is provided about the data items but one can guess that they are related to a particular car model and its launch date.

Tuples usually supports the sequence operations supported by string and lists:

>>> (1, 2) + (3, 4)  					 # Concatenation
(1, 2, 3, 4)
>>> (1, 2) * 3 						 # Repetition
(1, 2, 1, 2, 1, 2)
>>> A = (1, 2, 3, 4)  					# Indexing, slicing
>>> A[0],  A[1:3]
(1, (2, 3))

You should be very careful when you define tuple containing a single data item. Because this single item can be interpreted by Python compiler as an expression. To create a single item tuple, you should add a trailing comma after that item, just before the closing parentheses:

>>> x = (40)  							  # An integer!
>>> x
40
>>> y = (40,) 							 # A tuple containing an integer
>>> y
(40,)

It is not necessary to use parentheses in tuples, tuples values will work fine without them. But it is a good programing practice to include parentheses when creating tuples. The places, where the parentheses required for tuples are:

  • When nested in a larger expression or in a function call.
  • To differentiate items of the larger data structure like list or dictionary

For beginner, it is good to add parentheses when creating a tuple. It helps with the readability of the programs.

Conversions, methods, and immutability

Most of the tuples operations are similar to their other counterparts such as lists or string variables. But when we talks about +, * or slicing operations, these operations a new tuple when applied to a tuple. For example, to sort a tuple, first you will have to convert it to a list to make it mutable and then use the sorting method or you will have to use sorted() method:

Listing 7: Representing the sorting of tuple values

>>> O= ('kk', 'aa', 'dd', 'bb')
>>> tmp = list(O) 			 # Make a list from a tuple's items
>>> tmp.sort()  			 # Sort the list
>>> tmp
['aa', 'bb', 'dd', 'kk']
>>> O = tuple(tmp) 			 # Make a tuple from the list's items
>>> O
('aa', 'bb', 'dd', 'kk')
>>> sorted(T) 				 # Or use the sorted built-in, and save two steps
['aa', 'bb', 'dd', 'kk']

In listing 7, we used built-in tuple and list functions to convert the objects to a list and then back to the tuple.

We can use the list comprehensions to convert tuples. For example, in below example, we are creating a list from tuples, multiplying 10 to each item along the way:

Listing 8: Representing the list comprehension

>>> A = (1, 2, 3, 4, 5)
>>> A= [x * 10 for x in A]
>>> A
[21, 22, 23, 24, 25]

List comprehensions may be called iteration tools because besides always making a new list, they can be used to iterate over any sequence objects such as string, tuples or other lists.

Also, tuples have their two own methods defined in Python2.6 and 3.0 - index and count. They do the same thing for lists also but they are defined for tuple objects:

Listing 9: Representing the index and count methods

>>> T = (1, 2, 3, 2, 4, 2)  			# Tuple methods in 2.6, 3.0, and later
>>> T.index(2)  				# index of first appearance of 2
1
>>> T.index(2, 2)  				# index of the second appearance of 2 
3
>>> T.count(2) 			             # Return the numbers of 2’s?
3    

Before Python 2.6 and 3.0, there was no method available exclusively for tuple. One more thing is very important, tuples are immutable but if they have any other data structure nested in, such as a nested list, then the elements of list can change their places:

>>> B= (1, [2, 3], 4)
>>> B[1] = 'spam'  					# This fails: can't change tuple itself
TypeError: object doesn't support item assignment
>>> B[1][0] = 'spam'  					# This works: can change mutables inside
>>> B
(1, ['spam', 3], 4)

Records: Named Tuples

Python provides its user a large cache of both built-in data types as well as user created data types using the default ones. For example, we know that both dictionary and lists can be used to represent record like information and because of dictionary keys, they are more suitable to create these structure. But if we don’t have to change the position of stored data, than the tuples can be used to create the records with positions for record fields like this:

Listing 10: Representation of records stored in tuple

>>> alok = ('alok', 25, ['dev', 'mgr']) 				 # Tuple record
>>> alok
('alok', 25, ['dev', 'mgr'])
>>> alok[0], alok[2]  						# Access by position
('alok', ['dev', 'mgr'])

But as usual, field members of tuples have less information about the data stored than the keys of a dictionary. The same record of listing 10 is created using a dictionary in listing 11 below

Listing 11: Another representation of records stored in tuple
>>> alok = dict(name='alok', age=25, jobs=['dev', 'mgr']) 		 # Dictionary record
>>> alok
{'jobs': ['dev', 'mgr'], 'name': 'alok', 'age': 25}
>>> alok['name'], alok['jobs']  					# Access by key
('alok', ['dev', 'mgr'])

If a user wants, then he can convert parts of the dictionary to a tuple if needed:

>>> tuple(alok.values()) 					 # Values to tuple
(['dev', 'mgr'], 'alok', 25)
>>> list(alok.items())  						# Items to tuple list
[('jobs', ['dev', 'mgr']), ('name', 'alok'), ('age', 25)]

Except this, Python’s library’s collection module provides a utility called, namedtuple. This utility allows the values of tuples to be accessed by both attribute name and position and id needed, can be converted to dictionary like form for access by key:

Listing 12: Representation of namedtuple utility

>>> from collections import namedtuple  			# Import extension type
>>> Rec = namedtuple('Rec', ['name', 'age', 'jobs'])              # Make a generated class
>>> alok = Rec('alok', age=25, jobs=['dev', 'mgr'])  		# A named-tuple record
>>> alok
Rec(name='alok', age=25, jobs=['dev', 'mgr'])
>>> alok[0], alok[2]  						# Access by position
('alok', ['dev', 'mgr'])
>>> alok.name, alok.jobs 					# Access by attribute
('alok', ['dev', 'mgr'])

Named tuples are standards not core types. These are available in Python 2.6 and newer version and rely on features relatively modern by Python’s standards.

Conclusion

This is a basic question about tuples: why do we need tuple if we have list? The answer of this question can be that because the tuples are immutable, they provide some sort of integrity. A developer has the assurance when he uses tuple that it won’t be changed through another reference elsewhere in program. Except this, tuples can be used as dictionary keys where list can’t.



Have total 6+ years of experience in developing enterprise applications using DOT.NET 3.5 and 4.0(C#, VB.NET, ADO.NET, ASP.NET),java, JQuery, JSON, LINQ,WCF, MVC3, MVC4, Silverlight, SQL Server, mobile applications and Oracle etc ...

What did you think of this post?
Services
[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually – in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits – in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login