0% found this document useful (0 votes)
127 views31 pages

INT 213 Python Dictionaries

1. Dictionaries in Python use braces {} and contain keys and their associated values separated by colons. 2. Keys must be immutable like strings, numbers, or tuples while values can be any data type. 3. Dictionaries are accessed using keys and allow fast lookup of values using different data types as keys like numbers, strings etc.

Uploaded by

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

INT 213 Python Dictionaries

1. Dictionaries in Python use braces {} and contain keys and their associated values separated by colons. 2. Keys must be immutable like strings, numbers, or tuples while values can be any data type. 3. Dictionaries are accessed using keys and allow fast lookup of values using different data types as keys like numbers, strings etc.

Uploaded by

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

Dictionaries

The syntax provides useful type information. The square brackets indicate that it’s a
list. The parenthesis indicate that the elements in the list are tuples.
QUIZ
Which of the following statements create a
dictionary?

a) d = {}
b) d = {“john”:40, “peter”:45}
c) d = {40:”john”, 45:”peter”}
d) All of the mentioned
Items are accessed by their position in a dictionary
and All the keys in a dictionary must be of the same
type.
a. True
b. False
Dictionary keys must be immutable

a. True
b. False
In Python, Dictionaries are immutable

a. True
b. False
What will be the output of the following Python code snippet?
a={1:"A",2:"B",3:"C"}
for i,j in a.items():
print(i,j,end=" ")

a) 1 A 2 B 3 C
b) 1 2 3
c) A B C
d) 1:”A” 2:”B” 3:”C”
Select the correct way to print Emma’s age.
student = {1: {'name': 'Emma', 'age': '27', 'sex': 'Female'},
2: {'name': 'Mike', 'age': '22', 'sex': 'Male'}}

a. student[0][1]
b. student[1][“age”]
c. student[0][“age”]
Fibonacci using Dictionary
fib={0:0,1:1}
def fibo(n):
if(n==0):
return 0
if(n==1):
return 1
else:
for i in range(2, n+1):
fib[i]=fib[i-1]+fib[i-2]
return(fib)
print(fibo(5))
Iterate over Python dictionaries using for loops

d={'red':1,'green':2,'blue':3}
for color_key, value in d.items():
print(color_key,'corresponds to', d[color_key])

OUTPUT:

blue corresponds to 3
green corresponds to 2
red corresponds to 1

Remove a key from a Python dictionary

myDict = {'a':1,'b':2,'c':3,'d':4}  
print(myDict)  
if 'a' in myDict:   
    del myDict['a']  
print(myDict) 
OUTPUT:

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


{'d': 4, 'b': 2, 'c': 3}

Sort a Python dictionary by key

color_dict = {'red':'#FF0000',
'green':'#008000',
'black':'#000000',
'white':'#FFFFFF'}

for key in sorted(color_dict):


print(key,” :”, color_dict[key]))

OUTPUT:

black: #000000
green: #008000
red: #FF0000
white: #FFFFFF
Find the maximum and minimum value of a Python dictionary

my_dict = {'x':500, 'y':5874, 'z': 560}

key_max = max(my_dict.keys(), key=(lambda k: my_dict[k]))


key_min = min(my_dict.keys(), key=(lambda k: my_dict[k]))

print('Maximum Value: ',my_dict[key_max])


print('Minimum Value: ',my_dict[key_min])

OUTPUT:

Maximum Value: 5874


Minimum Value: 500
Concatenate two Python dictionaries into a new one

dic1={1:10, 2:20}  
dic2={3:30, 4:40}  
dic3={5:50,6:60}  
dic4 = {}  
for d in (dic1, dic2, dic3): dic4.update(d)  
print(dic4) 

OUTPUT:

{1: 10, 2: 20, 3: 30, 4: 40, 5: 50, 6: 60}

Test whether a Python dictionary contains a specific key


fruits = {}  
fruits["apple"] = 1  
fruits["mango"] = 2  
fruits["banana"] = 4  
if "mango" in fruits:  
    print("Has mango")  
else:  
    print("No mango")  

if "orange" in fruits:  
    print("Has orange")  
else:  
    print("No orange")  

OUTPUT:

Has mango
No orange
QUESTIONS
Q1:Write a Python script to add a key to a dictionary.

Sample Dictionary : {0: 10, 1: 20}


Expected Result : {0: 10, 1: 20, 2: 30}

Q2: Write a Python script to concatenate following dictionaries to create a new one.
Sample Dictionary : 
dic1={1:10, 2:20} 
dic2={3:30, 4:40} 
dic3={5:50,6:60}
Expected Result : {1: 10, 2: 20, 3: 30, 4: 40, 5: 50, 6: 60}

Q3: Write a Python script to check if a given key already exists in a dictionary.

Q4: Write a Python script to print a dictionary where the keys are numbers between 1 and 15 (both included) and
the values are square of keys. 

Sample Dictionary 
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81, 10: 100, 11: 121, 12: 144, 13: 169, 14: 196, 15: 225}
Q6: Write a Python script to merge two Python dictionaries.

Q7: Write a Python program to sum all the items in a dictionary.

Q8:  Write a Python program to multiply all the items in a dictionary.

Q9: Write a Python program to remove a key from a dictionary.

Q10: Write a Python program to remove duplicates from Dictionary.

Q11: Write a Python program to create and display all combinations of letters, selecting each letter from a
different key in a dictionary. 

Sample data : {'1':['a','b'], '2':['c','d']}


Expected Output: 
ac
ad
bc
bd
• Define a python function ‘indian_cricket(d)’ which reads a dictionary
of the following form and identifies the player with the highest total
score. The function should return a pair (playername, topscore),
where playername is the name of the player with the highest score
and topscore is the total runs scored by the player.
Input is: indian_cricket ({‘test1’:{‘Dhoni’:75, ‘Kohli’:170}, ‘test2’:{Dhoni’:
30, ‘Pujara’: 45}})

You might also like