Python Dictionary and Tuple - Module3
Python Dictionary and Tuple - Module3
Dictionaries are a useful data structure for storing data in Python because they are
capable of imitating real-world data arrangements where a certain value exists for a given
key.
○ The components of the dictionary were made using keys and values.
A dictionary is, in other words, a group of key-value pairs, where the values can be any
Python object. The keys, in contrast, are immutable Python objects, such as strings,
tuples, or numbers. Dictionary entries are ordered as of Python version 3.7. In Python 3.6
and before, dictionaries are generally unordered.
Curly brackets are the simplest way to generate a Python dictionary, although there are
other approaches as well. With many key-value pairs surrounded in curly brackets and a
colon separating each key from its value, the dictionary can be built. (:). The following
provides the syntax for defining the dictionary.
Syntax:
In the above dictionary Dict, The keys Name and Age are the strings which come under
the category of an immutable object.
Code
Output
<class 'dict'>
printing Employee data ....
{'Name': 'Johnny', 'Age': 32, 'salary': 26000, 'Company': TCS}
Python provides the built-in function dict() method which is also used to create the
dictionary.
Code
Output
Empty Dictionary:
{}
To access data contained in lists and tuples, indexing has been studied. The keys of the
dictionary can be used to obtain the values because they are unique from one another. The
following method can be used to access dictionary values.
Code
Output
ee["Company"])
Output
<class 'dict'>
printing Employee data ....
Name : Dev
Age : 20
Salary : 45000
Company : WIPRO
Python provides us with an alternative to use the get() method to access the dictionary
values. It would give the same result as given by the indexing.
The dictionary is a mutable data type, and utilising the right keys allows you to change its
values. Dict[key] = value and the value can both be modified. An existing value can also
be updated using the update() method.
Note: The value is updated if the key-value pair is already present in the dictionary.
Otherwise, the dictionary's newly added keys.
Example - 1:
Code
Output
Empty Dictionary:
{}
Example - 2:
Code
Output
<class 'dict'>
printing Employee data ....
Employee = {"Name": "Dev", "Age": 20, "salary":45000,"Company":"WIPRO"} Enter
the details of the new employee....
Name: Sunny
Age: 38
Salary: 39000
Company:Hcl
printing the new data
{'Name': 'Sunny', 'Age': 38, 'salary': 39000, 'Company': 'Hcl'}
The items of the dictionary can be deleted by using the del keyword as given below.
Code
1. Employee = {"Name": "David", "Age": 30,
"salary":55000,"Company":"WIPRO"}
2. print(type(Employee))
3. print("printing Employee data .... ")
4. print(Employee)
5. print("Deleting some of the employee data")
6. del Employee["Name"]
7. del Employee["Company"]
8. print("printing the modified information ")
9. print(Employee)
10. print("Deleting the dictionary: Employee");
11. del Employee
12. print("Lets try to print it again ");
13. print(Employee)
Output
<class 'dict'>
printing Employee data ....
{'Name': 'David', 'Age': 30, 'salary': 55000, 'Company': 'WIPRO'}
Deleting some of the employee data
printing the modified information
{'Age': 30, 'salary': 55000}
Deleting the dictionary: Employee
Lets try to print it again
NameError: name 'Employee' is not defined.
The last print statement in the above code, it raised an error because we tried to print the
Employee dictionary that already deleted.
The value connected to a specific key in a dictionary is removed using the pop() method,
which then returns the value. The key of the element to be removed is the only argument
needed. The pop() method can be used in the following ways:
Code
1. # Creating a Dictionary
2. Dict1 = {1: 'JavaTpoint', 2: 'Educational', 3: 'Website'}
3. # Deleting a key
4. # using pop() method
5. pop_key = Dict1.pop(2)
6. print(Dict1)
Output
Additionally, Python offers built-in functions popitem() and clear() for removing
dictionary items. In contrast to the clear() method, which removes all of the elements
from the entire dictionary, popitem() removes any element from a dictionary.
Iterating Dictionary
Example 1
Code
Output
Name
Age
salary
Company
Example 2
Code
Output
John
29
25000
WIPRO
Example - 3
Code
1. #for loop to print the values of the dictionary by using values() method.
2. Employee = {"Name": "John", "Age": 29, "salary":25000,"Company":"WIPRO"}
3. for x in Employee.values():
4. print(x)
Output
John
29
25000
WIPRO
Example 4
Code
1. #for loop to print the items of the dictionary by using items() method
2. Employee = {"Name": "John", "Age": 29, "salary":25000,"Company":"WIPRO"}
3. for x in Employee.items():
4. print(x)
Output
('Name', 'John')
('Age', 29)
('salary', 25000)
('Company', 'WIPRO')
1. In the dictionary, we cannot store multiple values for the same keys. If we pass more
than one value for a single key, then the value which is last assigned is considered as the
value of the key.
Code
1. Employee={"Name":"John","Age":29,"Salary":25000,"Company":"WIPRO","Na
me":
2. "John"}
3. for x,y in Employee.items():
4. print(x,y)
Output
Name John
Age 29
Salary 25000
Company WIPRO
2. The key cannot belong to any mutable object in Python. Numbers, strings, or tuples
can be used as the key, however mutable objects like lists cannot be used as the key in a
dictionary.
Code
Output
The built-in Python dictionary methods are listed below, along with a brief description.
○ len()
The dictionary's length is returned via the len() function in Python. The string is
lengthened by one for each key-value pair.
Code
Output
○ any()
Like how it does with lists and tuples, the any() method returns True indeed if one
dictionary key does have a Boolean expression that evaluates to True.
Code
Output
True
○ all()
Unlike in any() method, all() only returns True if each of the dictionary's keys contain a
True Boolean value.
Code
Output
False
○ sorted()
Like it does with lists and tuples, the sorted() method returns an ordered series of the
dictionary's keys. The ascending sorting has no effect on the original Python dictionary.
Code
Output
[ 1, 5, 7, 8]
The built-in python dictionary methods along with the description and Code are given
below.
○ clear()
Code
1. # dictionary methods
2. dict = {1: "Hcl", 2: "WIPRO", 3: "Facebook", 4: "Amazon", 5: "Flipkart"}
3. # clear() method
4. dict.clear()
5. print(dict)
Output
{}
○ copy()
Code
1. # dictionary methods
2. dict = {1: "Hcl", 2: "WIPRO", 3: "Facebook", 4: "Amazon", 5: "Flipkart"}
3. # copy() method
4. dict_demo = dict.copy()
5. print(dict_demo)
Output
○ pop()
Code
1. # dictionary methods
2. dict = {1: "Hcl", 2: "WIPRO", 3: "Facebook", 4: "Amazon", 5: "Flipkart"}
3. # pop() method
4. dict_demo = dict.copy()
5. x = dict_demo.pop(1)
6. print(x)
Output
popitem()
Code
1. # dictionary methods
2. dict = {1: "Hcl", 2: "WIPRO", 3: "Facebook", 4: "Amazon", 5: "Flipkart"}
3. # popitem() method
4. dict_demo.popitem()
5. print(dict_demo)
Output
○ keys()
Code
1. # dictionary methods
2. dict = {1: "Hcl", 2: "WIPRO", 3: "Facebook", 4: "Amazon", 5: "Flipkart"}
3. # keys() method
4. print(dict_demo.keys())
Output
dict_keys([1, 2, 3, 4, 5])
○ items()
Code
1. # dictionary methods
2. dict = {1: "Hcl", 2: "WIPRO", 3: "Facebook", 4: "Amazon", 5: "Flipkart"}
3. # items() method
4. print(dict_demo.items())
Output
dict_items([(1, 'Hcl'), (2, 'WIPRO'), (3, 'Facebook'), (4, 'Amazon'), (5, 'Flipkart')])
○ get()
Code
1. # dictionary methods
2. dict = {1: "Hcl", 2: "WIPRO", 3: "Facebook", 4: "Amazon", 5: "Flipkart"}
3. # get() method
4. print(dict_demo.get(3))
Output
○ update()
It mainly updates all the dictionary by adding the key-value pair of dict2 to this
dictionary.
Code
1. # dictionary methods
2. dict = {1: "Hcl", 2: "WIPRO", 3: "Facebook", 4: "Amazon", 5: "Flipkart"}
3. # update() method
4. dict_demo.update({3: "TCS"})
5. print(dict_demo)
Output
○ values()
It returns all the values of the dictionary with respect to given input.
Code
1. # dictionary methods
2. dict = {1: "Hcl", 2: "WIPRO", 3: "Facebook", 4: "Amazon", 5: "Flipkart"}
3. # values() method
4. print(dict_demo.values())
Output
dict_values(['Hcl', 'WIPRO', 'TCS'])
Code:
Output:
1. Dictionary.keys()
2. Dictionary.values()
3. Dictionary.items()
Returns the list of all the key-value pairs as tuples in the dictionary
Understanding:
We just used the methods already defined in Python to manipulate a dictionary in the
code. In the first statement, a dictionary is created. In the next three statements, we
used .keys(), .values() and .items() to prints the keys, values and the (key: value) pairs in
the dictionary.
Code:
Output:
Understanding:
There are two important points to be grasped from the above code:
1. If we iterate a variable 'i' over a dictionary in Python, the dictionary's keys will be
traversed.
2. Now, if we want the values the keys hold, we need to ask the dictionary for which
we use- dictionary [key].
These are the two things we've done in the code. First, we declared a dictionary and
printed it. Then, we traversed through the dictionary's keys using the variable 'i'. In the
next loop, we traversed through the keys and printed their values:
We can use the same loop for printing both keys and values:
1. for i in dictionary:
2. print (i, end = ' ')
3. print (dictionary [i], end = ' ')
4. print ()
Output:
We've already seen the method items (). We used it to print all the (key: value) pairs in
the dictionary as a list of tuples. For a more clear representation of every key-value pair
in the dictionary, we can iterate a variable on the method:
Code:
Output:
One Program using all types of Iteration Methods:
1. dictionary = {1: 'Hydrogen', 2: 'Helium', 3: 'Lithium'}
2. print ("\nThe dictionary: ", dictionary)
3. print ("\n")
4. print ("Without using the inbuilt functions: ")
5. print ("Keys and values in the dictionary: ")
6. for i in dictionary:
7. print ('key: ', i, end = ' ')
8. print ('value: ', dictionary [i], end = ' ')
9. print ()
10. print ("\nUsing the inbuilt functions: ")
11. print ("Keys in the dictionary: ", dictionary. keys ())
12. print ("Values in the dictionary: ", dictionary. values ())
13. print ("The data stored in the dictionary: ", dictionary. items ())
14. print ("\nTuple-wise representation: ")
15. for i in dictionary. items ():
16. print (i)
Output:
Summary:
In this Tutorial, we discussed:
3. Iterating over the dictionary with the use of inbuilt Python methods and without
the use of the inbuilt methods.
5. Tuple arrangement of all the key-value pairs in the dictionary using .items ().
Python Tuples
A comma-separated group of items is called a Python triple. The ordering, settled items,
and reiterations of a tuple are to some degree like those of a rundown, but in contrast to
a rundown, a tuple is unchanging.
The main difference between the two is that we cannot alter the components of a tuple
once they have been assigned. On the other hand, we can edit the contents of a list.
Example
○ Tuples are an immutable data type, meaning their elements cannot be changed
after they are generated.
○ Each element in a tuple has a specific order that will never change because
tuples are ordered sequences.
Forming a Tuple:
Any number of items, including those with various data types (dictionary, string, float,
list, etc.), can be contained in a tuple.
Code
Output:
Empty tuple: ()
Tuple with integers: (4, 6, 8, 10, 12, 14)
Tuple with different data types: (4, 'Python', 9.3)
A nested tuple: ('Python', {4: 5, 6: 2, 8: 2}, (5, 3, 5, 6))
Parentheses are not necessary for the construction of multiples. This is known as triple
pressing.
Code
Output:
(4, 5.7, 'Tuples', ['Python', 'Tuples'])
<class 'tuple'>
<class 'TypeError'>
Essentially adding a bracket around the component is lacking. A comma must separate
the element to be recognized as a tuple.
Code
Output:
<class 'str'>
<class 'tuple'>
<class 'tuple'>
Indexing
Indexing We can use the index operator [] to access an object in a tuple, where the index
starts at 0.
The indices of a tuple with five items will range from 0 to 4. An Index Error will be raised
assuming we attempt to get to a list from the Tuple that is outside the scope of the
tuple record. An index above four will be out of range in this scenario.
The method by which elements can be accessed through nested tuples can be seen in
the example below.
Code
Output:
Python
Tuple
tuple index out of range
tuple indices must be integers or slices, not float
l
6
○ Negative Indexing
The last thing of the assortment is addressed by - 1, the second last thing by - 2, etc.
Code
Output:
Slicing
Tuple slicing is a common practice in Python and the most common way for
programmers to deal with practical issues. Look at a tuple in Python. Slice a tuple to
access a variety of its elements. Using the colon as a straightforward slicing operator (:)
is one strategy.
To gain access to various tuple elements, we can use the slicing operator colon (:).
Code
Output:
Deleting a Tuple
A tuple's parts can't be modified, as was recently said. We are unable to eliminate or
remove tuple components as a result.
Code
Output:
Code
Tuple Methods
Like the list, Python Tuples is a collection of immutable objects. There are a few ways to
work with tuples in Python. With some examples, this essay will go over these two
approaches in detail.
○ Count () Method
The times the predetermined component happens in the Tuple is returned by the count
() capability of the Tuple.
Code
1. # Creating tuples
2. T1 = (0, 1, 5, 6, 7, 2, 2, 4, 2, 3, 2, 3, 1, 3, 2)
3. T2 = ('python', 'java', 'python', 'Tpoint', 'python', 'java')
4. # counting the appearance of 3
5. res = T1.count(2)
6. print('Count of 2 in T1 is:', res)
7. # counting the appearance of java
8. res = T2.count('java')
9. print('Count of Java in T2 is:', res)
Output:
Count of 2 in T1 is: 5
Count of java in T2 is: 2
Index() Method:
The Index() function returns the first instance of the requested element from the Tuple.
Parameters:
○ Start: (Optional) the index that is used to begin the final (optional) search: The
most recent index from which the search is carried out
○ Index Method
Code
1. # Creating tuples
2. Tuple_data = (0, 1, 2, 3, 2, 3, 1, 3, 2)
3. # getting the index of 3
4. res = Tuple_data.index(3)
5. print('First occurrence of 1 is', res)
6. # getting the index of 3 after 4th
7. # index
8. res = Tuple_data.index(3, 4)
9. print('First occurrence of 1 after 4th index is:', res)
Output:
First occurrence of 1 is 2
First occurrence of 1 after 4th index is: 6
Utilizing the watchword, we can decide whether a thing is available in the given Tuple.
Code
1. # Python program to show how to perform membership test for tuples
2. # Creating a tuple
3. tuple_ = ("Python", "Tuple", "Ordered", "Immutable", "Collection", "Ordered")
4. # In operator
5. print('Tuple' in tuple_)
6. print('Items' in tuple_)
7. # Not in operator
8. print('Immutable' not in tuple_)
9. print('Items' not in tuple_)
Output:
True
False
False
True
Code
Output:
Python
Tuple
Ordered
Immutable