Advance Python
Programming
Agenda
▰ Dictionary Comprehension
2
Dictionary Comprehension
▰ Python allows dictionary comprehensions. We can
create dictionaries using simple expressions. A
dictionary comprehension takes the form
▰ {key: value for (key, value) in iterable}
3
Back to main
Example:
Suppose we need to create a dictionary, of range 1- 20
contain only even numbers as Key and the value will
double of Key of that Even Number:
Write Code ?????
4
code :
dict = {}
For i in range(10):
if i%2==0:
dict[i] = i*2
print(dict)
Output
{0: 0, 2: 4, 4: 8, 6: 12, 8: 16}
5
Dictionary Comprehension syntax
{expression item For iterable}
new_dict = {i:i*2 for i in range(10) if i%2==0}
Print(new_dict)
6
Example 2 : cube of Numbers in Dictionary
cube = {}
for x in range (10):
if x % 2 == 0:
cube[i] = i**3
print(cube)
cube = [ expression for iterable range]
newdict = {x: x**3 for x in range(10)}
print(newdict)
{0: 0, 1: 1, 2: 8, 3: 27, 4: 64, 5: 125, 6: 216, 7: 343, 8: 512, 9: 729}
7
More Examples
▰ Given a dictionary {'Alice': 85, 'Bob': 90, 'Charlie':
75, 'David': 80}, create a new dictionary that keeps
only students who scored above 80.
Expected Output:
{'Alice': 85, 'Bob': 90}
▰ Given a list of words ["cat", "dog", "elephant"],
create a dictionary where keys are words, and values
are the words in uppercase.
▰ Expected Output:
{"cat": "CAT", "dog": "DOG", "elephant": "ELEPHANT"}
8
More Examples
▰ Given a dictionary {"a": 1, "b": 2, "c": 3, "d": 4},
create a new dictionary with keys and values
swapped.
Expected Output:
{1: "a", 2: "b", 3: "c", 4: "d"}
Given a string "hello", create a dictionary where keys
are characters and values are their ASCII values.
▰ Expected Output:
{'h': 104, 'e': 101, 'l': 108, 'o': 111}
9
Hint – ASCI Code for Characters
ord(character) # Built In function in Python
Char =‘A’
print(ord(char)
65 # ASCI code of A is 65
ord(character)
It takes a single character as input.
It returns the integer ASCII (or Unicode) code of that character.
A = 65
10