Best post on dictionary datatype in python – 1

Dictionary Datatype in Python

Python supports many simple and compound datatypes.

Few data types like list, dictionary are mutable and others like string datatype, tuple are immutable.

Mutable datatypes means changes can be done and are reflected in same variable.

Immutable datatypes means changes can be done but not in same variable.

 

What is dictionary?

Dictionary is an unordered collection of key-value pairs.

An empty dictionary represents zero character or we can call it as null dictionary indicating False boolean value.

A dict datatype can be defined with use of { key : value, key : value } pairs separated by comma.

Keys should be unique and values can have same data.

Keys defined must be of immutable datatype like string, integers, tuples etc. where as values can be mutable datatype.

But dictionary as a whole is a mutable datatype.

 

Example

>>> itv1={"name" : "Stark", "class" : "F Y C S", "roll no" : 1}
>>> itv1
{'roll no': 1, 'class': 'F Y C S', 'name': 'Stark'}
>>> type(itv1)
<class 'dict'>
>>>
itv1["name"] #key is used to access value

'Stark'
>>> itv1["roll no"] #key is used to access value
1
>>> itv1["class"] #key is used to access value
'F Y C S'
>>> itv1.keys()
dict_keys(['roll no', 'class', 'name'])
>>> itv1.values()
dict_values([1, 'F Y C S', 'Stark'])
>>>

In above example when we print itv1 the output order is not same as input order because dictionary is unorderd datatype.

itv1.keys() prints all the keys present in the dict.

itv1.values() prints all the values present in the dict.

 

Accessing a dictionary

Like list, tuple, string etc we do not have index value to access dictionary, we can access dictionary with the help of keys given.

A dict can be accessed using square brackets[ ] with key written inside it.

Example

>>> itv= {} #empty dictionary
>>> itv
{}
>>> itv1={1:'welcome',2:'to',3:'itvoyagers'}
>>> itv1[2]
'to'
>>> itv1[4]
Traceback (most recent call last):
File "<pyshell#8>", line 1, in <module>
itv1[4]
KeyError: 4
>>> itv1[0]
Traceback (most recent call last):
File "<pyshell#9>", line 1, in <module>
itv1[0]
KeyError: 0
>>>

 

Above example shows how an empty dictionary is defined. Also itv1 has 3 values with keys as  1,2,3 so while accessing the dictionary we use this keys and not the indexes so itv1[0] gives error as 0 is not the key also itv1[4] has 4 which is not available in dictionary.

len function or len()

Python provides a built-in function called as len() to calculate number of items in a dictionary or simply we can say length of a dictionary.

Example:

>>> itv1={"name" : "Stark", "class" : "F Y C S", "roll no" : 1}
>>> len(itv1)
3
>>> itv= {} #empty dictionary
>>> len(itv)
0

Above example calculates the length of dictionary by calculating number of pairs present.

Updating dictionary

You can update dictionary using update method.

A new key : value pair will be added or removed from dictionary to modify existing dictionary.

Example

#accessing values in dictionary
mydict={'Name':'sachin','Marks':50,'Subject':'python'}
print("mydict['Name']",mydict['Name'])
print("mydict['Marks']",mydict['Marks'])
print("mydict['Subject']",mydict['Subject'])
print("mydict before update()",mydict)

#update existing marks
mydict['Marks']=65
print("mydict['Marks']",mydict['Marks'])
print("mydict after update()",mydict)

dict1={'name':'riya','age':25,'rollno':5}
print("dict1 before update()",dict1)

#using update()
dict1.update({'fav_subject':'python'})
print("dict1 after update()",dict1)
 

OUTPUT

updating dictionary

Deleting items from dictionary

The del statement is used to delete items or pairs from dictionary.

It is possible to delete particular item from dictionary as it is of immutable datatype.

Also we can delete entire dict at at a time.

Example

del statement in dictionary

Properties of dictionary

There is no restriction on values of dictionary as we can have any datatype in place of value.

But for keys we have two properties to consider:

  • We cannot enter more than one entry per key. It means duplicate key is not allowed, but in case we create a duplicate key then the latest key will be considered.
>>> dict1={'age': 25, 'rollno': 5, 'name': 'riya', 'fav_subject': 'python'}
>>> dict1
{'age': 25, 'rollno': 5, 'name': 'riya', 'fav_subject': 'python'}
>>> dict1={'age': 25, 'rollno': 5, 'name': 'riya', 'fav_subject': 'python','rollno': 6}
>>> dict1
{'age': 25, 'rollno': 6, 'name': 'riya', 'fav_subject': 'python'}
>>>
  • As keys are immutable we can have integer,string or tuples as keys and not the mutable datatype.
>>> dict2={['name'] : 'strange','age':45}
Traceback (most recent call last):
File "<pyshell#38>", line 1, in <module>
dict2={['name'] : 'strange','age':45}
TypeError: unhashable type: 'list'
>>>

Other python related post

Best post on programming language and its types – 1
Python Programming (Basics) – History & Features
Python Programming (Basics)- Debugging & Types of errors
Python Programming (Basics) – Variables, Values, Types & Keywords.
Best post on built-in functions in python – 1
Python Programming (Basics) – Type Conversion
Python Programming (Basics) – Comments,Indentation,Built-in Number Data types and Expressions
Best post on IDLE & script mode in Python – 1
Python Programming (Basics)- Operators in Python
Best post on Order of Operations – Python
Simple and compound statements of python in easy way
Best post on conditional statements in python – Part 1
Best post on conditional statements in python – Part 2
Best post on looping in python (for loop)-Part 1
Best post on looping in python (while loop)-Part 2
Best post on nested loop in python(looping) -Part 3
Best post on infinite loop in python(looping) -Part 4
Best post on control statements(break,continue,pass)-1
Best post on Function definition & calling in python -1
Easy flow of function execution,parameters,arguments-2
Easy fruitful & void function,return values,stack diagrams-3
Best post on types of function arguments in python- 4
Best post on recursive function, scope of variable-5
Best post on import and from statement in python – 1
Best post on modules and built-in modules math,random & time-2
Best post on user defined modules in python-3
Best post on string datatype in python – 1
Best post immutable string,string operations python-2
Best post on string methods in python – 3
Best post on list datatype in python – 1
Best post on mutable list, list operations python – 2
Best post on List methods in python – 3
Best post on dictionary datatype in python – 1
Best post on dictionary methods and operations-2
Best post on tuple datatype in python – 1
Best post on tuple operations and immutable tuple- 2
Best post on tuple methods and built-in functions-3
17 -Python program to demonstrate Button in tkinter and its event in easy way
New posts coming soon…….

Other advance python related post

File Systems and File Handling in Python
Types of file modes and attributes of file object in Python
How to read,write and append in a file in python?
Remaining file methods in Python
File Positions in Python
Directory in Python and its methods
Iterator and Iterables in Python
Exceptions in Python
Exception Handling in Python (Part I)
Exception Handling in Python (Part II)
Regular Expressions
Metacharacters or Regular Expression Patterns
Functions in ‘re’ module(Part I)- Match vs Search
Functions in ‘re’ module(Part II)-findall(), split(), sub()
Flags for regular expressions(Modifiers)
GUI programming in Python and Python GUI Library
What is Tkinter ?
Layout Manager (Geometry Manager) in Python
Events and Bindings in Python along with Widget configuration and styling
Fonts Names, Font Descriptors, System Fonts, Text formatting, Borders, Relief Styles in Python
Best post:Dimensions, Anchors, Bitmaps & Cursors in Python
Canvas widget of tkinter module – Python
Widgets in tkinter module – Python
Label, Text, Entry & Message Widget in Python
Button, Checkbutton & Radiobutton Widget in Python
Best post on Menu and Menubutton Widget of tkinter
Best post- Listbox and Scrollbar(Slider) Widget-Python
Best post on Frame Widget of tkinter in Python
Best post: message box widget and its methods
Best post- LabelFrame, Toplevel, PanedWindow widgets
Best post on Spinbox and Scale Widget in Python
Best post : Database connectivity in Python (Part 1)
Best post : Database Connectivity in Python (Part 2)
Best post on Create and Insert query : Python + MySQL
New posts coming soon…….
We are aiming to explain all concepts of Python in easiest terms as possible.
ITVoyagers-logo
ITVoyagers
Author

Leave a Comment