You are on page 1of 30

PYTHON

DICTIONARY
Dictionary
• It is another collection in Python but with different in way of storing and
accessing. Other collection like list, tuple, string are having an index
associated with every element but Python Dictionary have a “key” associated
with every element. That’s why python dictionaries are known as
KEY:VALUE pairs.
• Dictionary is mutable. i.e, we can modify its contents(values). But, Key must
be unique and its immutable.
Dictionary
• Like with English dictionary we search any word for meaning associated with
it, similarly in Python we search for “key” to get its associated value rather
than searching for an index

{‘key’:’value’}
Characteristics
• Unordered set
• Not a sequence
• Indexed by Keys, Not Numbers
• Keys must be unique
• Mutable
• Internally stored as Mappings
Creating Dictionary
o Dictionary elements must be between curly brackets { }
o Each value must be paired with key element
o Each key-value pair must be separated by comma(,)

dictionary_name = {key1:value,key2:value,....}
Creating Dictionary
• EMPTY DICTIONARY
D = {} Or D = dict()

• my_dict = {1: 'apple', 2: 'ball',3:'cat'} Keys: 1,2,3


Values: apple, ball, cat

• my_dict = {'name': 'John', 1: [2, 4, 3]} Keys: name, 1


Values: John, [2,4,3]
Creating Using dict()
• You can use different methods to pass values into dict().
You can give key = value, [key, value], (key, value) etc.
• Giving as arguments e.g. Mydict=dict(1=‘apple’,2=‘ball’,3=‘cat’)
Or
• Passing as list e.g. Mydict=dict([[1,’apple’], [2,’ball’], [3,’cat’]])
Or
• Passing as tuple e.g. Mydict=dict(((1,’apple’), (2,’ball’), (3,’cat’)))
Creating Dictionary using { }
• DaysInMonth=
{"Jan":31,"Feb":28,"Mar":31,"Apr":31 "May":31,"Jun":30,"Jul":31,"Aug":31
"Sep":30,"Oct":31,"Nov":30,"Dec":31}
• Keys of dictionary must of immutable type such as: python string, number,
tuple
• If we try to give mutable type as key, python will give an error
• >>>dict2 = {[2,3]: “abc”} #Error
Accessing Dictionary
>>>dict1 = {'Mohan':95,'Ram':89,'Suhel':92, 'Sangeeta':85}
> > >dict1[‘Ram’]
89
>>>dict1[‘Suhel’]
92
> > >dict1[‘arun’]
KeyError: ‘arun’
Nesting Dictionaries
• You can add dictionary as value inside a dictionary. This type of dictionary
known as nested dictionary.
For example:
people = {'empcode':1,'bio': {'name': 'John', 'age': '27', 'sex': 'Male'}}
print(people['empcode'])
1
print(people['bio']) {'name': 'John', 'age': '27', 'sex': 'Male'}
print(people['bio']['name']) John
Adding New Item
• You can add new element to dictionary as :
• dictionaryName[“key”] = value

> > > dict1 = {'Mohan':95,'Ram':89,'Suhel':92, 'Sangeeta':85}


> > > dict1['Meena'] = 78
> > > dict1
{'Mohan': 95, 'Ram': 89, 'Suhel': 92, 'Sangeeta': 85, 'Meena': 78}
Updating Item
• You can update a element in dictionary as :
• dictionaryName[“key”] = value

> > > dict1 = {'Mohan':95,'Ram':89,'Suhel':92, 'Sangeeta':85}


#Marks of Suhel changed to 93.5
> > > dict1['Suhel'] = 93.5
> > > dict1{'Mohan': 95, 'Ram': 89, 'Suhel': 93.5, 'Sangeeta': 85}
Membership

• We can check the existence of key in dictionary using “in” and “not in
• If given key exists in dictionary then in operator will return true, false otherwise

> > > dict1 = {'Mohan':95,'Ram':89,'Suhel':92 > > > dict1 =


, 'Sangeeta':85} {'Mohan':95,'Ram':89,'Suhel':92,
> > > 'Suhel' in dict1 'Sangeeta':85}
True > > > 'Suhel' not in dict1
False
Deleting Item
• You can delete a element in dictionary as :
• del dictionaryName[“Key”]
>>> D1 = {1:10,2:20,3:30,4:40}
>>> del D1[2]
> > > D1
1:10,3:30,4:40
• If you try to remove the item whose key does not exists, the python runtime error
occurs.
Del D1[5] #Error
• del D1 will delete whole dictionary
Delete items using pop( )
• dictionaryName.pop(key)
> > > D1 = {1:10,2:20,3:30,4:40}
> > > D1.pop(2)
> > > 20
• if key passed to pop() doesn’t exists then python will raise an exception.
• Pop() function allows us to customized the error message displayed by use of
wrong key
Popping with custom message
> > > d1={'a': 'apple', 'b': 'ball', 'c': 'cat', 'd': 'dog'}
>>>d1.pop("a")
>>>d1
> > > {'b': 'ball', 'c': 'cat', 'd': 'dog'}
> > > d1.pop(“a”,‟Not found‟)
Not found
clear()
• Deletes or clear all the items of the dictionary
> > > d1 {'a': 'apple', 'b': 'ball', 'c': 'cat', 'd': 'dog'}
>>>d1.clear()
>>>d1
{}
Traversing
• Python allows to apply “for” loop to traverse every element of dictionary
based on their “key”. For loop will get every key of dictionary and we can
access every element based on their key.
d1={'a': 'apple', 'b': 'ball', 'c': 'cat', 'd': 'dog'}
for key in d1:
print(key,'=',d1[key])
keys()
keys() : this method return all the keys in the dictionary as a sequence of
keys(not in list form)
> > > mydict={'empno':1,'name':'Shivam','dept':'sales','salary':25000}
>>>mydict.keys()
l=mydict.keys()
dict_keys(['empno', 'name', 'dept', 'salary']) print(l[2]) #error

>>>l= list(my_dict.keys())
>>>l
['empno', 'name', 'dept', 'salary']
values()
values() : this method return all the values in the dictionary as a sequence of
values(not a list form)
> > > mydict={'empno':1,'name':'Shivam','dept':'sales','salary':25000}
>>>mydict.values() d1={'a': 'apple', 'b': 'ball', 'c': 'cat',
'd': 'dog'}
dict_values([1, 'Shivam', 'sales', 25000])
for key in d1.values():
print(key)
items()

items() : this method return all the values in the dictionary as a list of tuples
(key — value) pair
> > > mydict={'empno':1,'name':'Shivam','dept':'sales','salary':25000}
>>>mydict.items()
dict_items([('empno', 1), ('name', 'Shivam'), ('dept', 'sales'), ('salary', 25000)])
len()
len() : it return the length of dictionary i.e. the count of elements (key:value
pairs) in dictionary

>>>d1 = {'a': 'apple', 'b': 'boy', 'c': 'cat', 'd': 'dog'}


> > > len(d1)
4
get()
get() : this method is used value of given key, if key not found it raises an
exception
>>>d1.get(“b‟) # boy
>>>d1.get(“z‟) # Error, nothing will print

d1[‘key’] = d1.get(‘key’)
update()
update() merges the key:value pair from the new dictionary into original
dictionary, adding or replacing as needed. The items in the new dictionary are
added to the old one and override items already with the same keys
d1 = {'a': 'apple', 'b': 'boy', 'c': 'cat', 'd': 'dog'}
d2= {‘b’:’ball’,’c’:’cow’,’e’:’elephant’}
d1.update(d2) {'a': 'apple',
‘b’:’ball’,’c’:’cow’,’d’:’dog’,’e’:’elephant’}
print(d1)
min() & max()
• max() : this function return highest value in dictionary, this will work only if all the
values in dictionary is of numeric type
• min() :this function return lowest value in dictionary, this will work only if all the values
in dictionary is of numeric type.
my_dict = {1:500, 2:600, 4: 560}
print('Maximum Value: ',max(my_dict))
print('Minimum Value: ',min(my_dict))
print('Maximum Value: ',max(my_dict.values()))
print('Minimum Value: ',min(my_dict.values()))
sorted()
sorted() : this function is used to sort the key or value of dictionary in either
ascending or descending order. By default it will sort the keys.
sorted()
sorted() : this function is used to sort the key or value of dictionary in either
ascending or descending order. By default it will sort the keys.
Program to create dictionary from user input
Output
Create a dictionary by counting characters from
a string

You might also like