Dictionary Python
Dictionary Python
Week 8
Course: Programming in Python
CEC-Swayam/EMRC Dibrugarh University
Dictionary is a built-in Python Data
Structure and are used to store data
values in key:value pairs. Each key is
separated from its value by a colon ( : ).
Dictionaries
Dictionaries are not indexed by a
sequence of numbers but indexed
based on keys
Creating a Dictionary
• The syntax for defining a dictionary is:
• dictionary_name = {key_1: value_1, key_2: value2, key_3: value_3}
Points to
remember Dictionary are case-sensitive i.e. two keys with
similar name but different case will be treated
differently.
The elements within the dictionary are
accessed with the help of the keys rather than
its relative position.
"""Write a program to create a dictionary to convert values from
meters to centimeters
"""
mtocm={m:m*100 for m in range(1,11) }
print("Meters:Centimeters",mtocm)
"""
Write a program that creates a dictionary of cubes of odd numbers in
the range (1-10)
"""
cubes={c:c**3 for c in range(10) if c%2==1}
print(cubes)
"""
To count the number of occurrences of each character of a message
entered by the user.
"""
def cnt(msg):
lc={} #empty dictionary
for l in msg:
lc[l]=lc.get(l,0)+1
print(lc)
dict['emp2']['salary'] = 15500
print(dict)
# Program to print sum of key-value # pairs in dictionary
if emp1 == emp2:
print("emp1 and emp2 are same dictionaries")
else:
print("emp1 and emp2 are not same dictionaries")
if emp2 == emp3:
print("emp2 and emp3 are same dictionaries")
else:
print("emp2 and emp3 are not same dictionaries")
# Program to remove a key from dictionary using del in Python
# Sorting dictionary
sort_res = dict()