Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Python Dictionary

Download as pdf or txt
Download as pdf or txt
You are on page 1of 8

Python Notes Class XI Dictionary

A dictionary is a collection of pair of values. A pair is also called an element of the dictionary. All the
pairs (elements) in the dictionary are enclosed within {}. Every pair has two components separated by
colon (:). The value on the left-hand side of the colon (:) is the key. A key is immutable type like int or
float or str. Key can either be a constant or a variable. The value on the right-hand side of the colon (:) is
the value for the key. Value for the value can either be a constant or a variable or an expression. A
dictionary is a mutable type. In a dictionary key acts like an index for every element in the dictionary.
How to create a dictionary?

dictname={key1:value1, key2:value2, key3:value3,…}

>>> d1={1:1011, 2:'ABHIJIT', 3:78000.0}


>>> d2={1.5:1012, 2.5:'SUNIL', 3.5:75000.0}
>>> d3={'eno':1013, 'name':'KARAN', 'bsal':77000.0}
>>> eno, name, bsal =1014, 'DEEPAK', 76000.0
>>> d4={'eno':eno, 'name':name, 'bsal':bsal, 'hra':0.2*bsal}
>>> co,na,bs='code','name','bsal'
>>> code,name,bsal=1027,'RADHIKA SINHA',156000.0
>>> d5={co:code, na:name, bs:bsal}
>>> d6={} #d6=dict()

Dictionary d1 is created with 3 pairs. Key for every pair is an int type. Every value in the dictionary d1
is a constant. Dictionary d2 is created with 3 pairs. Key for every pair is a float type. Every value in the
dictionary d2 is a constant. Dictionary d3 is created with 3 pairs. Key for every pair is a str type. Every
value in the dictionary d3 is a constant. Dictionary d4 is created with 4 pairs. Key for every pair is a str
type. Values in the first 3 pairs are variable and value for the last pair is an expression. Dictionary ds is
created where keys are string (str) type variable and values are also variables. Dictionary d6 is created
as an empty dictionary (without any pair).

>>> print(d1)
Displays {1: 1011, 2:'ABIJEET', 3: 78000.0}

>>> print(d2)
Displays {1.5: 1012, 2.5: 'SUNIL', 3.5: 75000.0}

>>> print(d3)
Displays {'eno': 1013, 'name': 'KARAN', 'bsal': 77000.0}

>>> print(d4)
Displays {'eno': 1014, 'name': 'DEEPAK', 'bsal': 76000.0, 'hra': 15200.0}

>>> print(d5)
Displays {'code': 1027, 'name': 'RADHIKA SINHA', 'bsal': 156000.0}

>>> print(d6)
Displays {}

Keys in a dictionary are supposed to be distinct. But what happens when a key is repeated?
>>> stu={'rn':10, 'na':'TARUN', 'th':50, 'pr':25, 'th':55}
>>> print(stu)
Displays {'rn':10, 'na':'TARUN', 'th':55, 'pr':25}
In the dictionary stu, key 'th' is repeated twice. When a key is repeated, Python will take the last key
from the left and ignore the previous key(s). As displayed above, first 'th':50 is ignored but second
'th':55 is accepted.
FAIPS, DPS Kuwait Page 1 of 8 © Bikram Ally
Python Notes Class XI Dictionary
Function print(dictname) will display the entire dictionary. To display only the keys in dictionary
we can use keys() method of dictionary. Method keys() will display the keys of the dictionary as a
list. To display the only values in dictionary we can use values() method of dictionary. Method
values() will display the values of the dictionary as a list.

>>> print(d1.keys())
Displays dict_keys([1, 2, 3])

>>> print(d2.keys())
Displays dict_keys([1.5, 2.5, 3.5])

>>> print(d3.keys())
Displays dict_keys(['eno', 'name', 'bsal'])

>> print(d4.keys())
Displays dict_keys(['eno', 'name', 'bsal', 'hra'])

>> print(d5.keys())
Displays dict_keys(['code', 'name', 'bsal'])

>>> print(d6.keys())
Displays dict_keys([])

>>> print(d1.values())
Displays dict_values([1011, 78000.0])

>>> print(d2.values())
Displays dict_values([1012, 'SUNIL', 75000.0])

>>> print(d3.values())
Displays dict_values([1013, 'KARAN', 77000.0])

>>> print(d4.values())
Displays dict_values([1014, 'DEEPAK', 76000.0, 15200.0])

>>> print(d5.values())
Displays dict_values(1027, 'RADHIKA SINHA', 156000.0])

>>> print(d6.values())
Displays dict_values([])

As mentioned earlier, a key in a dictionary can either be int or float or str or any other immutable type.
Normally, by convention key is a str type. We will follow the convention and use str type for a key.. To
access a particular value in a pair (element of a dictionary), we need the key for that pair since key acts as
an index for every pair in the dictionary. A value in a dictionary is accessed as:

dictname['key']=newvalue #updates the value of ‘key'


print(dictname['key']) #displays the value for the 'key'

>>> stu={'rn':24, 'na':'TARUN', 'th':50.5, 'pr':25.5}


>>> print(stu['rn'], stu['na'], stu['th'], stu['pr'])
Displays 24 TARUN 50.5 25.5

FAIPS, DPS Kuwait Page 2 of 8 © Bikram Ally


Python Notes Class XI Dictionary
>>> stu['th'], stu['pr']=52.0, 27.0 #update keys 'th','pr'
>>> print(stu['rn'], stu['na'], stu['th'], stu['pr'])
Displays the updated value as 24 TARUN 52.0 27.0

To append new key(s) in a dictionary


1. Add a new key using = operator
>>> stu={'rn':24, 'na':'TARUN', 'th':45}
>>> stu['th']=47 #updates key 'th'
>>> stu['pr']=25 #appends a new key 'pr':25
>>> stu['tt']=72 #appends a new key 'th':72
>>> print(stu)
Displays {'rn':24, 'na':'TARUN', 'th':47, 'pr':25, 'tt':70}
OR,
Append a new keys using dictionary method update()
>>> stu={'rn':24, 'na':'TARUN', 'th':47}
>>> stu.update({'pr':25, 'tt':72}) #appends new keys 'pr' and 'tt'
>>> print(stu)
Displays {'rn':24, 'na':'TARUN', 'th':47, 'pr':25, 'tt':72}

2. Appending a new dictionary to an existing dictionary


We can add more than one keys by using the method described in 1. But we can use dictionary method
update() to add more than one keys in a dictionary in one go.
>>> stu={'rn':24, 'na':'TARUN'}
>>> print(stu)
Displays {'rn':24, 'na':'TARUN'}
>>> stu.update({'th',47, 'pr',27, 'tt',72})
Add new keys 'th':45, 'pr':27 and 'tt':72 in the dictionary stu.
To add more than one keys, another dictionary is passed as a parameter to update() function.
>>> print(stu)
Displays {'rn':24, 'na':'TARUN', 'th':45, 'pr':27, 'tt':72}
OR,
>>> stu={'rn':24, 'na':'TARUN'}
>>> marks={'th':47, 'pr':27, 'tt':72}
>>> stu.update(marks)
>>> print(stu)
Displays {'rn':24, 'na':'TARUN', 'th':45, 'pr':27, 'tt':72}

Using operators, keywords and built-in functions used with dictionary:


Creates a new dictionary
>>> stu={'rn':24, 'na':'TARUN', 'th':47.0}
= >>> print(stu)
Displays {'rn':24, 'na':'TARUN', 'th':47.0}
Updating a key in a dictionary the exists
>>> stu={'rn':24, 'na':'TARUN', 'th':47}
= >>> stu['th']=50
>>> print(stu)
Displays {'rn':24, 'na':'TARUN', 'th':50}
A new key is appended to a dictionary if the key does not exist
>>> stu={'rn':24, 'na':'TARUN', 'th':47}
= >>> stu['pr']=24
>>> print(stu)
Displays {'rn':24, 'na':'TARUN', 'th':47, 'pr':24}

FAIPS, DPS Kuwait Page 3 of 8 © Bikram Ally


Python Notes Class XI Dictionary
Creates a new dictionary which is an alias of an existing dictionary
>>> stu1={'rn':24, 'na':'TARUN'}
>>> stu2=stu1
The dictionary stu2 is created as an alias of stu1 since dictionary is mutable type. Since
dictionaries stu1 and stu2 share same memory location, any change in stu1 will
update stu2 and vice-versa.
=
>>> stu1['th']=50 #New key 'th' is appended to stu2
>>> stu2['th']=53 #Updates 'th' of stu1
>>> print(stu1)
Displays {'rn':24, 'na':'TARUN', 'th':53}
>>> print(stu2)
Displays {'rn':24, 'na':'TARUN', 'th':53}
Deletes an element or elements from a dictionary
>>> stu={'rn':24, 'na':'TARUN', 'th':47, 'pr':27, 'tt':74}
del >>> del stu['pr'], stu['tt'] #delete keys 'pr','tt'
>>> print(stu)
Displays {'na':'TARUN', 'th':47}
Deletes a dictionary
>>> stu={'rn':24, 'na':'TARUN', 'th':47}
del >>> del stu
>>> print(stu)
Displays syntax error because the dictionary stu has been deleted from the memory
Checks whether a key is in a dictionary
>>> stu={'rn':24, 'na':'TARUN', 'th':47}
>>> print('na' in stu)
in
Displays True, since key 'na' is in the dictionary stu
>>> print('pr' in stu)
Displays False, since key 'pr' is not in the dictionary stu
Returns the length of a dictionary
>>> stu={'rn':24, 'na':'TARUN', 'th':47}
len()
>>> print(len(stu))
Displays 3, since there are 3 elements (3 pairs) in the dictionary stu
Method min() returns the lowest key in the dictionary
Method max() returns the highest key in the dictionary
>>> stu={'rn':24, 'na':'TARUN', 'th':47}
>>> print(min(stu), max(stu))
Displays na th since from the list of keys ['rn', 'na', 'th'], 'na' is the lowest
value and 'th' is the highest value.
>>> stu={1:24, 2:'TARUN', 3:47}
>>> print(min(stu), max(stu))
Displays 1 3
max() >>> stu={1.0:24, 2.0:'TARUN', 3.0:47}
min() >>> print(min(stu), max(stu))
Displays 1.0 3.0
>>> stu={1:24, 2.0:'TARUN', 3:47, 4.0:26}
>>> print(min(stu), max(stu))
Displays 1 4.0
>>> stu={'1':24, 2:'TARUN', 3.0:47}
>>> print(min(stu))
Displays run-time error since integer, float and string cannot be compared
>>> print(max(stu))
Displays run-time error since integer, float and string cannot be compared

FAIPS, DPS Kuwait Page 4 of 8 © Bikram Ally


Python Notes Class XI Dictionary
Returns the sum of the keys in the dictionary
>>> stu={1:24, 2:'TARUN', 3:47}
>>> print(sum(stu))
Displays 6
>>> stu={1.0:24, 2.0:'TARUN', 3.0:47}
>>> print(sum(stu))
Displays 6.0
>>> stu={1:24, 2.0:'TARUN', 3:47, 4.0:26}
sum()
>>> print(sum(stu))
Displays 10.0
>>> stu={1:24, '2':'TARUN', 3.0:47}
>>> print(sum(stu))
Displays run-time error since integer, float and string cannot be added
>>> stu={'rn':24, 'na':'TARUN', 'th':47}
>>> print(sum(stu))
Displays run-time error since strings cannot be added
Returns the keys as a sorted list
>>> stu={2:24, 1:'TARUN', 4:47, 3:27}
>>> print(sorted(stu))
Displays [1, 2, 3, 4]
>>> stu={2.1:24, 1.2:'TARUN', 4.5:47, 3.4:27}
>>> print(sorted(stu))
Displays [1.2, 2.1, 3.4, 4.5]
>>> stu={1:24, 2.0:'TARUN', 3:47, 4.0:26}
sorted()
>>> print(sorted(stu))
Displays [1, 2.0, 3, 4.0]
>>> stu={'rn':24, 'na':'TARUN', 'th':47}
>>> print(sorted(stu))
Displays ['na', 'rn', 'th']
>>> stu={1:24, '2':'TARUN', 3.0:47}
>>> print(sorted(stu))
Displays run-time error since integer, float and string cannot be compared
Displays a dictionary
>>> stu={'rn':24, 'na':'TARUN', 'th':47}
print()
>>> print(stu)
Displays {'rn':24, 'na':'TARUN', 'th':47}

Methods from dictionary


Removes all elements (pairs) from a dictionary
>>> stu={'rn':24, 'na':'TARUN', 'th':47}
>>> stu.clear()
clear()
Removes / deletes all the keys from the dictionary.
>>> print(stu, len(stu))
Displays {} 0 #stu is empty => len(stu) is 0 (zero)
Creates a duplicate of an existing dictionary
>>> stu1={'rn':24, 'na':'TARUN', 'th':47}
>>> stu2=stu1.copy()
The dictionary stu2 is a copy of the dictionary stu1. Dictionaries stu1 and stu2
copy()
share two different memory locations. Updating stu1 will not update stu2 and
vice-versa.
>>> stu1['pr']=28 #New key 'pr' is appended to stu1
>>> print(stu1)

FAIPS, DPS Kuwait Page 5 of 8 © Bikram Ally


Python Notes Class XI Dictionary
Displays {'rn':24, 'na':'TARUN', 'th':47, 'pr':28}
>>> print(stu2)
Displays {'rn':24, 'na':'TARUN', 'th':47}, dictionary stu2 is not
updated
Returns value for the key present in the dictionary
>>> stu={'rn':24, 'na':'TARUN', 'th':47, 'pr':28, 'tt':75}
>>> print(stu.get('tt'))
Displays 75 since value for the key 'tt' is 75
>>> print(stu.get('gr'))
Displays None since the key 'gr' is not present in stu.
get()
>>> print(stu.get('gr', 'C1'))
Displays C1 since the key 'gr' is not present in stu but returns the default value
>>> print(stu['th']) #same as stu.get('th')
Displays 47 since value for the key 'th' is 47
>>> print(stu['gr'])
Displays run-time error since key 'gr' is not present in stu.
Returns keys stored in a dictionary as an iterable object
>>> stu={'rn':24, 'na':'TARUN', 'th':47}
>>> print(stu.keys())
Displays dict_keys(['rn', 'na', 'th'])
>>> for key in stu: print(key, stu[key])
Displays
rn 24
keys()
na TARUN
th 47
>>> for key in stu.keys(): print(key, stu[key])
Displays
rn 24
na TARUN
th 47
Returns values stored in a dictionary as an iterable object
>>> stu={'rn':24, 'na':'TARUN', 'th':47.5}
values()
>>> print(stu.values())
Displays dict_values([24, 'TARUN', 47.5])
Deletes a key from a dictionary and returns its value
>>> stu={'rn':24, 'na':'TARUN', 'th':47, 'pr':28, 'tt':75}
>>> print(stu.pop('tt'))
Displays 75, value for the key 'tt' and the key 'tt' is deleted from the dictionary
stu
pop() >>> print(stu)
Displays {'rn':24, 'na':'TARUN', 'th':47, 'pr':28}
>>> print(stu.pop('gr'))
Displays run-time error since key 'gr' is not present in the dictionary stu
>>> print(stu.pop())
Displays run-time error since pop() method of dictionary needs one argument
Deletes last key from a dictionary and returns its value
>>> stu={'rn':24, 'na':'TARUN', 'th':47, 'pr':28}
>>> print(stu.popitem())
popitem() Displays ('pr', 28), value for the last key pair and the key 'pr' is deleted from
the dictionary stu
>>> print(stu)
Displays {'rn':24, 'na':'TARUN', 'th':47}

FAIPS, DPS Kuwait Page 6 of 8 © Bikram Ally


Python Notes Class XI Dictionary
>>> print(stu.popitem('th'))
Displays run-time error since method popitem() does not have any argument
Returns a list containing every key pair value as an iterable object
>>> stu={'rn':24, 'na':'TARUN', 'th':47, 'pr':28}
>>> print(stu.items())
Displays [('rn',24), ('na','TARUN'), ('th',47), ('pr',28)]
Kindly note every key pair value is represented as a tuple in the list.
items() >>> for key, val in stu.items(): print(key, val)
Displays
rn 24
na TARUN
th 47
pr 28
Creates a new dictionary from keys
>>> stu=dict.fromkeys(['rn', 'na', 'th'])
>>> print(stu)
Displays {'rn': None, 'na': None, 'th': None}
>>> mykeys=['roll', 'name', 'theo']
>>> stu=dict.fromkeys(mykeys, '***')
Method fromkeys() with two arguments: first argument (argument from left) is either
fromkeys()
a list or a tuple and second argument (argument from right) is a single value for every
key.
>>> print(stu)
Displays {'roll':'****', 'name':'****', 'theo':'****'}
>>> mykeys=('roll', 'name', 'theo')
>>> stu=dict.fromkeys(mykeys, 100)
Displays {'roll':100, 'name':100, 'theo':100}
Returns the value of the key present in the dictionary (similar to method get()). If
the key does not exist, new key is appended to the dictionary (similar to method
update())
>>> stu={'rn':24, 'na':'TARUN', 'th':47, 'pr':28}
>>> print(stu.setdefault('na')) #same as stu.get('na')
Displays TARUN since value for the key 'na' is TARUN
>>> print(stu.setdefault('na', 'SANDIP'))
Displays TARUN since value for the key 'na' is TARUN and the default value is
setdefault() ignored
>>> print(stu.setdefault('tt'))
Displays None since the key 'tt' is not present in the dictionary stu
>>> print(stu.setdefault('tt', 75))
Displays 75 since the key 'tt' is not present in the dictionary stu, the default value
is displayed and the key 'tt' is appended to the dictionary stu (similar to method
update())
>>> print(stu)
Displays {'rn':24, 'na':'TARUN', 'th':47, 'pr':28, 'tt':75}
update() Appends key(s) to a dictionary
Discussed in details earlier

1. Create a Python dictionary student with following keys:


roll integer (student roll number)
name string (student name)
marks a list of floating-point values with 5 elements (marks of 5 subjects)
Append following keys in the dictionary student:

FAIPS, DPS Kuwait Page 7 of 8 © Bikram Ally


Python Notes Class XI Dictionary
total floating point (total of 5 subjects marks)
agg floating point (aggregate percentage = total/5)
Input values for key roll, name and marks. Calculate value for keys total and agg. Display student
dictionary on the screen.
ro=int(input('Roll? '))
na=input('Name? ')
ma,tm=[], 0
for k in range(5):
t=float(input('Marks? '))
ma+=[t]
tm+=t
student={'roll':ro, 'name':na, 'marks':ma}
student['total']=tm
student['agg']=tm/5
print(student)
OR,
student = { 'roll':int(input('Roll? ')),
'name':input('Name? '),
'marks':[int(input('Marks? ')) for k in range(5)] }
student['total']=sum(student['marks'])
student['agg']=student['total']/5
print(student)

2. Write a Python script to create dictionary employee with following keys:


code integer (employee code)
name string (employee name)
bsal floating point (basic salary)
Edit the dictionary employee by adding following keys:
hra floating point (house rent = 25% of basic salary)
da floating point (dearness allowance = 85% of basic salary)
gsal floating point (gross salary = basic salary + house rent + dearness allowance)
itax income tax and it is calculated as:
Gross Salary Income Tax
<=200000 0% of Gross Salary
>200000 and <=500000 5% of Gross Salary
>500000 and <=1000000 7% of Gross Salary
>1000000 10% of Gross Salary
Input value for keys code, name and bsal. Calculate value for keys hra, da, gsal and itax. Display
dictionary employee on the screen.
employee={ 'code':int(input('Code? ')),
'name':input('Name? '),
'bsal': float(input('BSal? ')) }
employee['hra']=0.25*employee['bsal']
employee['da']= 0.85*employee['bsal']
employee['gsal']=employee['bsal']+employee['hra']+employee['da']
gsal=employee['gsal']
if gsal<=200000: bo=0.0
elif gsal<=500000: bo=0.05*gsal
elif gsal<=1000000: bo=0.07*gsal
else: bo=0.10*gsal
employee['itax']=itax
for key in employee.keys(): print(key,employee[key])

FAIPS, DPS Kuwait Page 8 of 8 © Bikram Ally

You might also like