You are on page 1of 20

DICTIONARIES

What is a dictionary?

• Dictionary is a data structure just like list.


• It is also termed as an associative array,
associative list, a map or hash.
• Dictionaries are mutable,unordered collections
with elements in the form of a key: value pairs.
• We can think it as, a list of pairs, where the first
element of the pair, the key, is used to retrieve
the second element, the value.
• Thus we map a key to a value
Creating Python Dictionary
dicName={key1:value1, key2:value2……}
• Key must be immutable type
– strings, integers, float, tuples
– lists and dictionaries are NOT
• Value can be anything like string, float, integer, list,
Tuple etc….
Example:
contacts={'bill':'353-1234',
'rich':'269-1234','jane':'352-1234’ }
Mapping
Dictionary keys can be any immutable object
demo1 = {2: [‘a’,’b’,’c’], (2,4): 27, ‘x’: 12.5, “ab”:3}
>>>print (demo1[2])
[‘a’, ‘b’, ‘c’]
>>>print (demo1[(2,4)])
27
>>>print(demo1 [‘x’])
12.5
>>>print(demo[‘ab’])
3
Creating empty dictionary
a)Telephone={}
b)Telephone=dict() (constructor method)
Adding/ updating value to a dictionary
Syntax: dictionay [<key>]=<value>
Example:
>>>Telephone [‘avi’]=‘9876545444’
>>>print(Telephone) # {'avi': '9876545444’}
>>>Telephone [‘atul’]=‘9415099991’
>>>print(Telephone)
{'avi': '9876545444', 'atul': '9415099991’}
>>>Telephone [‘avi’]=’2345124’
>>>print(Telephone)
#{'avi': '2345124', 'atul': '9415099991’}
Collection but not sequences
Dictionaries are collections but they are not
sequences such as lists, strings or tuples
–there is no order to the elements of a
dictionary
–in fact, the order (for example,
when printed might change as elements
are added or deleted.)
Access requires [ ], but the key is the index!
Syntax: dic name[key]
mydic={} #an empty dictionary
mydic['bill']=25
Mydic[1]=“DVD”
– added the pair 'bill':25
>>>print(mydic['bill'],mydic[1])
– prints 25 DVD
>>>print(mydic) #{‘bill’:25,1:”DVD”}
(dictionary name without key prints
The entire dictionary content)
• Checking for existing key
By using in and not in membership operators:
• key in dictionary (returns true if key exist else
false)
• key not in dictionary (returns true if key does not
exist else false)
Example: mydic = {'bill':3, 'rich':10}
>>>’bill’ in mydic
True
>>>’billing’ in mydic
False
Traversing a Dictionary
Means accessing and processing each element of the
Dictionary.
•Using for loop :- Syntax:
for variable in dictionary:
process
Example:
dic={2:"qaz",(6,7):5,'y':['m','n','k'],"aa":(9,0)}
for i in dic:
print( i," ",dic[i])
OUTPUT:
2 qaz
(6, 7) 5
y ['m', 'n', 'k']
aa (9, 0)
DICTIONARY FUNCTIONS AND
METHODS
• len():
It returns the length of the dictionary.
Every key-value pair adds 1 to the length.
Syntax: len(dictionaryname)
Example:
mydic = {'bill':3, 'rich':10}
>>> len(mydic)
Output: 2
• keys()
It returns a list of keys in a Python
dictionary.
Syntax: dictionaryname.keys()
Example:
>>> mydic.keys()
OUTPUT:
dict_keys([‘bill’,’rich’])
• values()
It returns a list of values in the
dictionary.
Syntax: dictionaryname.values()
Example:

>>> mydic.values()

dict_values([3,10])

19-12-2021
• get()
It takes one to two arguments. Where the
first is the key to search for,(if key found it
returns the value) the second is the value to
return if the key isn’t found.
The default value for this second argument
is None.
Syntax:
dictionaryname.get(key,returnvalue)
Example:
dict4={1:11,2:22,3:33,4:44}
>>> dict4.get(3,0) # 33
>>> dict4.get(5,0) # 0
>>> dict4.get(5) # None
NOTE : Since the key 5 wasn’t in the
dictionary, it returned 0, like we
specified and None when not given
>>>dict4.get(7,'not')
'not'
19-12-2021
• clear()
It empties the dictionary.
Syntax: dictionaryname.clear()
Example:
>>> dict4.clear()
It can be reassigned for further use.
>>> dict4={3:3,1:1,4:4}
( It is possible)
• items()
It returns a list of key-value pairs.
Syntax:
dictionaryname.items()
Example:
>>> dict4.items()
dict_items([(3, 3), (1, 1), (4, 4)])

19-12-2021
• update()
It takes another dictionary as argument.
Then it updates the dictionary to hold values
from the other dictionary that it doesn’t have
already.
>>> dict1={1:1,2:2}
>>> dict2={2:20,3:3}
>>> dict1.update(dict2)
>>> dict1
{1: 1, 2: 20, 3: 3}
• Deleting elements from a dictionary
A) del command Syntax: del DicName[key]
Example:
>>> mydic = {'bill':3, 'rich':10}
>>>del mydic[‘bill’]
>>>print (mydic) #{‘rich’:10}
B) By using pop() function : Syntax: dictionary.pop(key)
Example: >>>mydic.pop(‘bill’)
3
( pop() will also return the value which has been deleted)
>>>print(mydic) #{‘rich’:10}
NOTE: del dic Name will delete the entire dictionary.
Like : del mydic # it will delete the dictionary

You might also like