Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
41 views

Dictionaries in Python

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
41 views

Dictionaries in Python

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 12

Dictionaries in Python

Questions & Notes

Question : How are dictionaries different from lists ?


Answer: The dictionary is similar to lists in the sense that it is also a collection of data-items just
like lists but it is different form lists in the sense that lists are sequential collections and
dictionaries are non-sequential collections.

In lists, where there is an order associated with the data items because they act as storage units
for other objects or variables created. Dictionaries are different from lists and tuples because the
group of objects they hold are not in any particular order, but rather each object has its own
unique name, commonly known as a key.

Question : When are dictionaries more useful than lists ?


Answer: Dictionaries can be much more useful than lists. For example : suppose we wanted to
store all our friend’s cell phone numbers. We could create a list of pairs (phone number, name),
but once this list becomes long enough searching this list for a specific phone number will get
time consuming. Better would be if we could index the list by our friend’s name. This is
precisely what a dictionary does.

Question : What is a key-value pair with reference to Python dictionary ?


Answer:
A dictionary is a mapping between a set of indices (which are called keys) and a set of values.
Each key maps a value. The association of a key and a value is called a key-value pair.

Question : What are the characteristics of Python Dictionaries ?


Answer:
The 3 main characteristics of a dictionary are :

1. Dictionaries are Unordered : The dictionary elements (key-value pairs) are not in ordered
form.
2. Dictionary Keys are Case Sensitive : The same key name but with different case are
treated as different keys in Python dictionaries.
3. No duplicate key is allowed : When duplicate keys encountered during assignment, the
last assignment wins.
4. Keys must be immutable : We can use strings, numbers or tuples as dictionary keys but
something like [‘key’] is not allowed.

Question : Why are dictionaries called mutable types?

Answer

Dictionaries can be changed by adding new key-value pairs and by deleting or changing the
existing ones. Hence they are called as mutable types.
For example:
d = {"a" : 1 , "b" : 2}
d["c"] = 3
d["b"] = 4
del d["a"]
print(d)
Output
{'b': 4, 'c': 3}

dict["c"] = 3 adds a new key-value pair to dict.


dict["b"] = 4 changes existing key-value pair in dict.
del dict["a"] removes the key-value pair "a" : 1

Question : What are different ways of creating dictionaries?

Answer

The different ways of creating dictionaries in Python are:

1. By using curly brackets and separating key-value pairs with commas as per the syntax below:

<dictionary-name> = {<key>:<value>, <key>:<value>...}

For example:

d = {'a': 1, 'b': 2, 'c': 3}

2. By using dictionary constructor dict(). There are multiple ways to provide keys and values to
dict() constructor:

i. Specifying key:value pairs as keyword arguments to dict() function:


For example:

Employee = dict(name = 'john' , salary = 1000, age = 24)


print(Employee)
Output
{'name': 'john', 'salary': 1000, 'age': 24}

ii. Specifying keys and its corresponding values separately:


Keys and Values are enclosed separately in parentheses and are given as arguments to zip()
function.
For example:

Employee = dict(zip(('name','salary','age'),('John',10000,24)))
Output
{'name': 'John', 'salary': 10000, 'age': 24}

Question : What values can we have in a dictionary?

Answer

A dictionary can have values of all data types i.e., integers, floats, strings, booleans, sequences
and collections, etc. For example:
d = {1:'a' , 2: 2 , 3: True , 4: 3.5 , 5: "python",(1,2,3) : 4}

Question : How are individual elements of dictionaries accessed?

Answer : Individual elements of a dictionary can be accessed by using their corresponding keys
as per the syntax shown below:

<dictionary-name> [<key>]

For example:

d = {'a': 1, 'b': 2, 'c': 3}


print(d['a'])
Output
1

In addition to this, we can also use the get( ) method to get value of the given key as per the
syntax shown below:

<dictionary-name>.get(<key>, [default])

For example:

d = {'a': 1, 'b': 2, 'c': 3}


print(d.get('a'))
Output
1

Question : How is indexing of a dictionary different from that of a list or a string?

Answer : In lists or strings, the elements are accessed through their index where as in
dictionaries, the elements are accessed through the keys defined in the key:value pairs.

Moreover, lists and strings are ordered set of elements but dictionaries are unordered set of
elements so its elements cannot be accessed as per specific order.

Question : What do you understand by ordered collection and unordered collection ? Give
examples.

Answer : Ordered Collection is the one in which the position of each element is fixed.
Example: List, strings, Tuples

Unordered Collection is the one in which position of each element is not fixed i.e., the order of
all the elements are not maintained.
Example: Sets, Dictionaries

Question : How do you add key:value pairs to an existing dictionary?

Answer

There are three ways by which new key:value pairs can be added to an existing dictionary:
1. By using assignment as per the following syntax:

<dictionary>[<key>] = <value>

For example:

d = {1 : 'a' , 2 : 'b'}
d[3] = 'c'
print(d)
Output

{1: 'a', 2: 'b', 3: 'c'}

2. By using update() method:


update() method merges key:value pairs from new dictionary into the original dictionary adding
or replacing as needed. The syntax to use this method is:

<dictionary>.update(<other-dictionary>)

For example:

d = {1 : 'a' , 2 : 'b'}
d.update({3 : 'c'})
print(d)
Output

{1: 'a', 2: 'b', 3: 'c'}

Question : Can you remove key:value pairs from a dictionary and if so, how?

Answer : Yes, key:value pairs can be removed from a dictionary. The different methods to
remove key:value pairs are given below:

1. By using del command:


It is used to delete an item with the specified key name. The syntax for doing so is as given
below:

del <dictionary>[<key>]

For example:

dict = {'list': 'mutable', 'tuple': 'immutable', 'dictionary': 'mutable'}


del dict["tuple"]
print(dict)
Output
{'list': 'mutable', 'dictionary': 'mutable'}

2. By using pop() method:


This method removes and returns the dicitionary element associated to the passed key. It is used
as per the syntax:

<dict>.pop(key, <value>)

For example:
dict = {'list': 'mutable', 'tuple': 'immutable', 'dictionary': 'mutable'}
dict.pop("tuple")
print(dict)
Output
{'list': 'mutable', 'dictionary': 'mutable'}

3. popitem() method:
This method removes and returns the last inserted item in the dictionary. It is used as per the
syntax:

<dict>.popitem()

For example:

dict = {'list': 'mutable', 'tuple': 'immutable', 'dictionary': 'mutable'}


dict.popitem()
print(dict)
Output
{'list': 'mutable', 'tuple': 'immutable'}

Here, the last element of dict was 'dictionary': 'mutable' which gets removed by function
popitem().

Question : 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 ?

Answer : 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. Instead we can add a new key : value
pair with the desired key and delete the previous one.
For example:

d = { 1 : 1 }
d[2] = 2
print(d)
d[1] = 3
print(d)
d[3] = 2
print(d)
del d[2]
print(d)
Output
{1: 1, 2: 2}
{1: 3, 2: 2}
{1: 3, 2: 2, 3: 2}
{1: 3, 3: 2}
Explanation

d is a dictionary which contains one key-value pair.


d[2] = 2 adds new key-value pair to d.
d[1] = 3 modifies value of key 1 from 1 to 3.
d[3] = 2 adds new key-value pair to d.
del d[2] deletes the key 2 and its corresponding value.
Question : How is clear( ) function different from del <dict> statement ?

Answer : The clear( ) function removes all the key:value pairs from the dictionary and makes
it empty dictionary while del <dict> statement removes the complete dictionary as an object.
After del statement with a dictionary name, that dictionary object no more exists, not even empty
dictionary.
For example:

d = {1: 'a' , 2 : 'b'}


d.clear()
print(d)
del d
print(d)
Output
{}
NameError: name 'd' is not defined.

Question : How is pop( ) different from popitem( ) ?

Answer

The differences between pop( ) and popitem( ) are mentioned below:

pop( ) popitem( )

pop( ) removes the item with the specified popitem( ) removes the last inserted item from the
key name. dictionary.

With pop( ), we can specify a return value With popitem( ), we cannot specify any such
or a message if the given key is not found message/return value while deleting from an empty
in the dictionary. dictionary. It will raise an error in this case.

Question : What is the use of copy( ) function ?

Answer

The copy() function is used to create a shallow copy of a dictionary where only a copy of keys is
created and the values referenced are shared by the two copies.
For example:

original_d = {1:'a', 2:'b'}


new_d = original_d.copy()
print(new_d)
Output

{1: 'a', 2: 'b'}

Here, original_d and new_d are two isolated objects, but their contents still share the same
reference i.e ('a','b')

Question : The following code is giving some error. Find out the error and correct it.
d1 = {"a" : 1, 1 : "a", [1, "a"] : "two"}
Answer

This type of error occurs when a mutable type is used as a key in dictionary. In d1, [1, "a"] is
used as a key which is a mutable type of list. It will generate the below error:

TypeError: unhashable type: 'list'

This error can be fixed by using a tuple as a key instead of list as shown below:

d1 = {"a" : 1, 1 : "a", (1, "a") : "two"}

Question : The following code has two dictionaries with tuples as keys. While one of these
dictionaries being successfully created, the other is giving some error. Find out which
dictionary will be created successfully and which one will give error and correct it :

dict1 = { (1, 2) : [1, 2], (3, 4) : [3, 4]}


dict2 = { ([1], [2]) : [1,2], ([3], [4]) : [3, 4]}

Answer

dict1 will be created successfully because tuples are used as keys. As tuples are immutable,
therefore it won't give any error.

dict2 will give an error because the tuples used as keys of dict2 contain lists as their elements. As
lists are mutable, so they can't appear in keys of the dictionary.

It can be corrected by removing list elements from the tuples as shown below:
dict2 = { (1,2) : [1,2], (3,4) : [3, 4]}

Question : What is the output produced by the following code :

d1 = {5 : [6, 7, 8], "a" : (1, 2, 3)}


print(d1.keys())
print(d1.values())

Answer

Output
dict_keys([5, 'a'])
dict_values([[6, 7, 8], (1, 2, 3)])
Explanation

keys() function returns all the keys defined in the dictionary in the form of a list. values()
function returns all the values defined in the dictionary in the form of a list.

Question : Consider the following code and then answer the questions that follow :

myDict = {'a' : 27, 'b' : 43, 'c' : 25, 'd' : 30}


valA =''
for i in myDict :
if i > valA :
valA = i
valB = myDict[i]
print(valA) #Line1
print(valB) #Line2
print(30 in myDict) #Line3
myLst = list(myDict.items())
myLst.sort() #Line4
print(myLst[-1]) #Line5

1. What output does Line 1 produce ?


2. What output does Line 2 produce ?
3. What output does Line 3 produce ?
4. What output does Line 5 produce ?
5. What is the return value from the list sort( ) function (Line 4) ?

Answer

1. The output of line 1 is : 'd'


2. The output of line 2 is: 30
3. The output of line 3 is: False
Since 30 is present in myDict as a value and not as a key.
4. The output of line 5 is: ('d',30)
myLst is a list which is created by dictionary items i.e myDict.items()
Hence, myLst will store ⇒ [('a', 27), ('b', 43), ('c', 25), ('d', 30)]
myLst.sort() will sort the list in ascending order according to the first element of each tuple.
Since the first elements of the tuples are all strings, Python performs lexicographical sorting,
which means that 'a' comes before 'b' and so on.
myLst[-1] will return last element of list i.e.,('d', 30).
5. The sort function in Line 4 will not return any value.
It will sort myLst in place in ascending order according to the first element of each tuple. Since
the first elements of the tuples are all strings, Python performs lexicographical sorting, which
means that 'a' comes before 'b' and so on. The sorted myLst will be [('a', 27), ('b',
43), ('c', 25), ('d', 30)]

Question : What will be the output produced by following code ?

d1 = { 5 : "number", "a" : "string", (1, 2): "tuple" }


print("Dictionary contents")
for x in d1.keys(): # Iterate on a key list
print (x, ':' , d1[x], end = ' ')
print (d1[x] * 3)
print ( )

Answer

Output
Dictionary contents
5 : number numbernumbernumber

a : string stringstringstring

(1, 2) : tuple tupletupletuple


Explanation

d1 is a dictionary containing three key-value pairs.


x in d1.keys() represents that x will iterate on the keys of d1.
The iterations are summarized below:
x d1[x] d1[x] * 3

5 number numbernumbernumber

a string stringstringstring

(1,2) tuple tupletupletuple

Question : Write a program to enter names of employees and their salaries as input and
store them in a dictionary.

Solution
d = {}
ans = "y"
while ans == "y" or ans == "Y" :
name = input("Enter employee name: ")
sal = float(input("Enter employee salary: "))
d[name] = sal
ans = input("Do you want to enter more employee names? (y/n)")
print(d)
Output
Enter employee name: Kavita
Enter employee salary: 35250.50
Do you want to enter more employee names? (y/n)y
Enter employee name: Rakesh
Enter employee salary: 27000
Do you want to enter more employee names? (y/n)n
{'Kavita': 35250.5, 'Rakesh': 27000.0}

Question : Write a program to count the number of times a character appears in a given
string.

Solution
str = input("Enter the string: ")
ch = input("Enter the character to count: ");
c = str.count(ch)

print("Count of character",ch,"in",str,"is :", c)


Output
Enter the string: appoggiatura
Enter the character to count: a
Count of character a in appoggiatura is : 3

Question : Write a program to convert a number entered by the user into its
corresponding number in words. For example, if the input is 876 then the output should be
'Eight Seven Six'.
(Hint. use dictionary for keys 0-9 and their values as equivalent words.)

Solution
num = int(input("Enter a number: "))
d = {0 : "Zero" , 1 : "One" , 2 : "Two" , 3 : "Three" , 4 : "Four" , 5 :
"Five" , 6 : "Six" , 7 : "Seven" , 8 : "Eight" , 9 : "Nine"}
digit = 0
str = ""
while num > 0:
digit = num % 10
num = num // 10
str = d[digit] + " " + str

print(str)
Output
Enter a number: 589
Five Eight Nine

Question : Repeatedly ask the user to enter a team name and how many games the team
has won and how many they lost. Store this information in a dictionary where the keys are
the team names and the values are lists of the form [wins, losses].

(a) Using the dictionary created above, allow the user to enter a team name and print out the
team's winning percentage.

(b) Using the dictionary, create a list whose entries are the number of wins of each team.

(c) Using the dictionary, create a list of all those teams that have winning records.

Solution
d = {}
ans = "y"
while ans == "y" or ans == "Y" :
name = input("Enter Team name: ")
w = int(input("Enter number of wins: "))
l = int(input("Enter number of losses: "))
d[name] = [w, l]
ans = input("Do you want to enter more team names? (y/n): ")

team = input("Enter team name for winning percentage: ")


if team not in d:
print("Team not found", team)
else:
wp = d[team][0] / sum(d[team]) * 100
print("Winning percentage of", team, "is", wp)

w_team = []
for i in d.values():
w_team.append(i[0])

print("Number of wins of each team", w_team)

w_rec = []
for i in d:
if d[i][0] > 0:
w_rec.append(i)

print("Teams having winning records are:", w_rec)


Output
Enter Team name: masters
Enter number of wins: 9
Enter number of losses: 1
Do you want to enter more team names? (y/n): y
Enter Team name: musketeers
Enter number of wins: 6
Enter number of losses: 4
Do you want to enter more team names? (y/n): y
Enter Team name: challengers
Enter number of wins: 0
Enter number of losses: 10
Do you want to enter more team names? (y/n): n
Enter team name for winning percentage: musketeers
Winning percentage of musketeers is 60.0
Number of wins of each team [9, 6, 0]
Teams having winning records are: ['masters', 'musketeers']

Question : Write a program that repeatedly asks the user to enter product names and
prices. Store all of these in a dictionary whose keys are the product names and whose
values are the prices.

When the user is done entering products and prices, allow them to repeatedly enter a product
name and print the corresponding price or a message if the product is not in the dictionary.

Solution
d = {}
ans = "y"
while ans == "y" or ans == "Y" :
p_name = input("Enter the product name: ")
p_price = float(input("Enter product price: "))
d[p_name] = p_price
ans = input("Do you want to enter more product names? (y/n): ")

ans = "y"
while ans == "y" or ans == "Y" :
p_name = input("Enter the product name to search: ")
print("Price:", d.get(p_name, "Product not found"))
ans = input("Do you want to know price of more products? (y/n): ")
Output
Enter the product name: apple
Enter product price: 165.76
Do you want to enter more product names? (y/n): y
Enter the product name: banana
Enter product price: 75
Do you want to enter more product names? (y/n): y
Enter the product name: guava
Enter product price: 48.5
Do you want to enter more product names? (y/n): n
Enter the product name to search: apple
Price: 165.76
Do you want to know price of more products? (y/n): y
Enter the product name to search: tomato
Price: Product not found
Do you want to know price of more products? (y/n): n

Question : Can you store the details of 10 students in a dictionary at the same time ?
Details include - rollno, name, marks, grade etc.

Give example to support your answer.

Solution
n = 10
details = {}

for i in range(n):
name = input("Enter the name of student: ")
roll_num = int(input("Enter the roll number of student: "))
marks = int(input("Enter the marks of student: "))
grade = input("Enter the grade of student: ")
details[roll_num] = [name, marks, grade]
print()
print(details)
Output
Enter the name of student: Sushma
Enter the roll number of student: 4
Enter the marks of student: 56
Enter the grade of student: C

Enter the name of student: Radhika


Enter the roll number of student: 3
Enter the marks of student: 90
Enter the grade of student: A+

Enter the name of student: Manika


Enter the roll number of student: 45
Enter the marks of student: 45
Enter the grade of student: D

Enter the name of student: Mitanshu


Enter the roll number of student: 1
Enter the marks of student: 23
Enter the grade of student: F

Enter the name of student: Anshika


Enter the roll number of student: 7
Enter the marks of student: 77
Enter the grade of student: B

Enter the name of student: Purva


Enter the roll number of student: 9
Enter the marks of student: 99
Enter the grade of student: A+

Enter the name of student: Sanjana


Enter the roll number of student: 3
Enter the marks of student: 76
Enter the grade of student: B+

Enter the name of student: Priyanka


Enter the roll number of student: 2
Enter the marks of student: 89
Enter the grade of student: A

Enter the name of student: Anand


Enter the roll number of student: 6
Enter the marks of student: 100
Enter the grade of student: A+

Enter the name of student: Sarika


Enter the roll number of student: 10
Enter the marks of student: 55
Enter the grade of student: B+

{4: ['Sushma', 56, 'C'], 3: ['Sanjana', 76, 'B+'], 45: ['Manika', 45, 'D'],
1: ['Mitanshu', 23, 'F'], 7: ['Anshika', 77, 'B'], 9: ['Purva', 99, 'A+'], 2:
['Priyanka', 89, 'A'], 6: ['Anand', 100, 'A+'], 10: ['Sarika', 55, 'B+']}

You might also like