0% found this document useful (0 votes)
16 views7 pages

Gr11 Ch.12 Dictionaries

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views7 pages

Gr11 Ch.12 Dictionaries

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 7

Computational Thinking and Programming-1

CHAPTER 14: DICTIONARIES


I. ANSWER THE FOLLOWING IN ONE OR TWO SENTENCES :
1. Write a short note on Dictionaries.
The data type dictionary is a mapping between a set of keys and a set of values.
 The key-value pair is called an item.
 A key is separated from its value by a colon(:) and consecutive items are
separated by commas.
 Items in dictionaries are unordered, so we may not get back the data in the same
order in which we had entered the data initially in the dictionary.
2. How will you creating a Dictionary?
To create a dictionary, the items entered are separated by commas and enclosed in
curly braces. Each item is a key value pair, separated through colon (:).
3. How will you traversing a dictionary?
We can access each item of the dictionary or traverse a dictionary using for loop.
>>> d = {'Arun':95,'Ram':89,'Saran':92}
>>> for key in d:
print(key,':',d[key])
Arun : 95
Ram : 89
Saran : 92
4. Why is a dictionary termed as an unordered collection of objects?
Dictionary is termed as an unordered collection of objects because the printed
order of elements is not same as the order in which the elements are stored.
Python dictionaries are not intended to be in order, as simple as that. If we want
to collect a set of objects in order, we have only one choice of accessing them: through
index.
5. What type of objects can be used as keys in dictionaries?
Keys must be immutable.
Dictionary keys must be of an immutable type. Strings and numbers are the two
most commonly used data types as dictionary keys. We can also use tuples as keys but
they must contain only strings, integers, or other tuples. We have already created a
dictionary with integer keys. For example, you can use an integer, float, string, or
Boolean as a dictionary key.
6. Though tuples are immutable type, yet they cannot always be used as keys in
dictionary. What is the condition to use tuples as a key in dictionary?
Tuples can be used as a key in a dictionary only when it contains immutable type
elements. Though tuples are immutable type, yet they cannot always be used as keys in
a dictionary. Tuple must be contain immutable datatype / element .
7. What are the types of values can you store in : a. dictionary – values ?
b. dictionary – keys?
The dictionary stores objects as key-value pairs and can be used to represent complex
real-world data.
Python allows the values in a dictionary to be any type – string, integer, a list, another
dictionary, boolean, etc. However, keys must always be an immutable data type, such as
strings, numbers, or tuples.
8. Can you change the order of dictionary’s contents, i.e. can you sort the contents of a
dictionary?
No, the contents of a dictionary cannot be sorted in place like that of a list. However, we
can indirectly sort the keys and values of a dictionary by using sorted() function:
sorted(dictionary).

1
Computational Thinking and Programming-1

9. In no more than one sentence, explain the following python error and how it could
arise : TypeError: unhashable type: ‘list’
The Python TypeError: unhashable type: 'list' usually means that a list is being
used as a hash (#) argument. This error occurs when trying to hash a list, which is an
unhashable object.
It means that you have tried to assign a key with mutable type and python
dictionary do not allow this.
10. Can you check for a value inside a dictionary using in operator? How will you
check for a value inside a dictionary using in operator?
You can use the in operator to check if a key exists in a dictionary. It's one of the
most straight forward ways of accomplishing the task. When used, it returns either a
True if present and a False if otherwise.
11. Dictionary is a mutable type, which means you can modify its contents? What all is
modifiable in a dictionary? Can you modify the keys of a dictionary?
Yes, we can modify the contents of a dictionary. Values of key-value pairs are
modifiable in dictionary. New key-value pairs can also be added to an existing
dictionary and existing key-value pairs can be removed. However, the keys of the
dictionary cannot be changed.
12. How is del D and del D[<key>] different from one another if D is a dictionary?
del D is used to delete the whole dictionary while del D[<key>] is used to delete
only the key: value pair with the given key. del d #d is deleted and becomes not defined.
13. How is clear( ) functions different from del<dict> statement?
clear( ) function delete the all keys and values in the dictionary and leave the
dictionary empty. While del <dict> delete the complete dictionary when we want to find
deleted dictionary then it will give error that <dict> not defined.
14. What does fromkeys( ) method do?
The Python fromkeys() built-in function generates a new dictionary from the
specified sequence of elements as keys and a user-supplied value. Python fromkeys()
dictionary class method is used to create and return a new dictionary from a passed set
of sequences as keys along with a value provided by the user.
15. How is pop( ) different from popitem( )?
Although we use pop() and popitem() to remove elements from a dictionary, they
are actually different. pop() can remove any item from a dictionary as long as you
specify the key. On the other hand, popitem() can only remove and return the value of
the last element in the dictionary.
16. If sorted( ) is applied on a dictionary, What does it return?
If only sorted() is applied on dictionary then it considers only the keys of the
dictionary for sorting and returns a sorted list of the dictionary keys.
17. Will max() and min() always work for a dictionary?
No, max( ) and min( ) will not always work for a dictionary. They will only work
with dictionaries having homogeneous keys that can be compared. (Yes, if the
dictionary keys have homogeneous data-types).
18. What do you understand by shallow copy of a dictionary?
A shallow copy of an object is a copy whose properties share the same references (point
to the same underlying values) as those of the source object from which the copy was
made. i.e. A shallow copy of a dictionary refers to a copy of the dictionary whereby only
a copy of references (the keys) is created and the content (values of the dictionary) is
not copied.

2
Computational Thinking and Programming-1

19. What is the use of copy( ) function?


The copy() method returns a copy of the specified list.
The Copy function takes any text value and copies it to the clipboard. Regardless
of the contents of the text, the clipboard will contain plain text without any special mime
type. The function is considered a side-effects function and as a result it can only be
used in behavior properties.
20. Discuss the working of copy( ) if i) the values are of immutable types,
ii) the value are of mutable types.
If the values are of immutable types then any changes made in the copy created
with copy( ) will not be reflected in the original dictionary.
d1 = {1:'Neha' , 2: 'Saima' , 3: 'Avnit' , 4: 'Ana'}
d2 = d1.copy()
d2[5] = 'Taru'
print(d2)
print(d1)
Output:
{1: 'Neha', 2: 'Saima', 3: 'Avnit', 4: 'Ana', 5: 'Taru'}
{1: 'Neha', 2: 'Saima', 3: 'Avnit', 4: 'Ana'}
(ii) the values are of mutable types:
If the values are of mutable types then any changes made in the copy created with
copy() will be reflected in the original dictionary.
For example:
d1 = {1:[1,2,3] , 2: [3,4,5]}
d2 = d1.copy()
d2[1].append(4)
print(d2)
print(d1)
Output:
{1: [1, 2, 3, 4], 2: [3, 4, 5]}
{1: [1, 2, 3, 4], 2: [3, 4, 5]}

3
Computational Thinking and Programming-1

21. Dictionary methods and Built-in-Functions:-


Python provides many functions to work on dictionaries.

get( ) d1.get(key,[default]) Returns corresponding value if the key


d1={1:“one”, 2: “Two”, 3: “Three”} exists, else it returns python’s Error if
d1.get(3) default argument is missing otherwise
“Three” returns default argument.
popitem( ) <dict>.popitem( ) Removes the last key value pair of
d1.popitem( ) the dictionary, and returns a (key,
3:Three value) pair from the dictionary
sorted(<dict>) d1={100:240, 25:90, 5:45.55, 0:“XI”} Returns a sorted list in ascending order
[reverse=True] sorted(d1) – sorted(d1)
sorted( d1, reverse=True) Returns a sorted list in
d1={0:”XI”, 5:45.55, 25:90, 100:240} descending order – sorted (d1, reverse =
d1={100:240, 25:90, 5:45.55, 0:”XI”} True)
min(<dict>) d1={100:240, 25:90, 5:45.55, 0:“XI”} Give the minimum key, maximum key,
max(<dict>) min(d1) sum of keys from the dictionary.
sum(<dict>) 0 I. In dictionary if we are using
max(d1) numeric data type you are
able to access min, max and
100
sum.
Sum(d1) II. In dictionary if we are using
130 string data type you are able
to access min, max. sum is
not possible in character and
string data type.
III. In mixed data type min, max
and sum is not possible.
Example :
d1={1:5, “x”:“sun”, 1.5:2, “name”:“Gr.11”}

4
Computational Thinking and Programming-1

CHAPTER 9: PYTHON MODULES


Definition:-

 Python standard library also consists of a number of modules.


 While a function is a grouping of instructions, a module is a grouping of
functions.
 To use a module, we need to import the module. Once we import a module, we
can directly use all the functions of that module.
Syntax
import modulename

 This gives us access to all the functions in the module(s). To call a function of a
module, the function name should be preceded with the name of the module with
a dot(.) as a separator.
 The syntax is as shown below:
modulename.functionname()
Built-in Modules:-

 Python library has many built-in modules that are really handy to programmers.
These modules are math, random, statistics.
math Module : It contains different types of mathematical functions. Most of the
functions in this module return a float value. In order to use the math module we need
to import it using the following statement:
import math

5
Computational Thinking and Programming-1

Function Syntax Meaning Example


math.sin(x) sine of x in radians >>> math.sin(0)
0
math.sqrt(x) square root of x >>> math.sqrt(144)
12.0
math.pow(x,y) xy (x raised to the power y) >>> math.pow(3,2)
9.0
math.factorial(x) factorial of x >>> math.factorial(5)
120
math.ceil(x) ceiling value of x >>> math.ceil (9.7)
10
math.fabs(x) absolute value of x >>> math.fabs(-4)
4.0

random Module :It contains functions that are used for generating random numbers.
For using this module, we can import it using the following statement:
import random

Function Syntax Meaning Example


random.random() Random Real Number (float) >>> random.random()
in the range 0.0 to 1.0 0.65333522
random. randint(x,y) Random integer between x >>> random.randint(3,7)
and y 4
random. randrange(x,y) Random integer between x >>> random.randrange(2,7)
and y 2

statistics Module :It provides functions for calculating statistics of numeric data.
It can be included in the program by using the following statements:
import statistics

Function Syntax Meaning Example


statistics.mean(x) arithmetic mean >>> statistics.
mean([11,24,32,45,51])
32.6
statistics.median(x) median (middle value) of x >>>statistics.
median([11,24,32,45,51])
32
statistics.mode(x) mode (the most repeated value) >>> statistics.
mode([11,24,11,45,11])
11
>>> statistics.
mode(("red","blue","red"))

6
Computational Thinking and Programming-1

'red'

You might also like