Best post on dictionary methods and operations-2

Dictionary operations and methods in python

Python supports various compound datatypes like dictionary, tuple,string etc.

We have already seen dictionary and its properties.

In this post we will be concentrating on various dictionary methods.

Dictionary consist of various methods for easy functioning and utilization of python script.

Operations in dictionary are traversing and appending new items.

Many methods like keys(), items(), values(), update() etc are used to provide various functionalities and can be used again and again as per need without need of coding again this helps in reducing redundancy. 

Operations in dictionary

We have already seen creation of dictionary, initialization, deletion and updating dictionary.

Apart from this dictionary operations we will be seeing other operations like traversing a dictionary and appending new elements or items to dictionary.

List of dictionary operations

  • Traversing a dictionary
    • It is used to traverse through dictionary elements.
    • Membership operators in and not in is used for traversing through the dictionary elements.
    • To display all the keys in itv
      • #to display all the keys in itv
        itv={'1':'pink','2':'blue','3':'black'}
        print("itv =",itv)
        for i in itv:
        print(i)
    • Output:
      • >>> 
        itv = {'2': 'blue', '3': 'black', '1': 'pink'}
        2
        3
        1
    • To display key :  value pairs from itv
      • itv={'1':'pink','2':'blue','3':'black'}
        print("itv =",itv)
        for m,n in itv.items():
        print(m,n)
    • Output:
      • itv = {'1': 'pink', '3': 'black', '2': 'blue'}
        1 pink
        3 black
        2 blue
  • Appending elements in dictionary
    • Appending is adding new value with the existing items of the dictionary
    • To append new element we need to use  = operator.
      • itv={'1':'pink','2':'blue','3':'black'}
        print("itv =",itv)
        #appending a value
        itv[4]='yellow'
        print("itv =",itv)
    • Output:
      • itv = {'2': 'blue', '3': 'black', '1': 'pink'}
        itv = {4: 'yellow', '2': 'blue', '3': 'black', '1': 'pink'}

Methods of dictionary

Dictionary has many built-in methods to support functionalities like fetching keys, values, items, length etc.

List of dictionary methods

  • len()

    • It returns total length of dictionary. 
    • The length is an integer value of number of items present in the dictionary.
    • len(dict)
    • The parameter dict is the dictionary whose length needs to be calculated.
  • clear()
    • This methods is used to remove all the items from the dictionary.
    • It does not return any value.
    •  dict.clear()
  • get()
    • This method is used to give the value of given key.
    • If the given key is not available then it will return the default value none.
    • dict.get(key,default=None)
    • The parameter key is the key which is to be searched in the dictionary.

  • update()
    • This method is used to add the key values of one dictionary to another dictionary.
    • This function does not return anything it just updates teh dictionary
    • dict1.update(dict2)
    • The parameter dict1 will get updated with items present in dict2.
  • keys()
    • It returns list of all keys present in given dictionary.
    • dict.keys()
    • Above syntax shows that all keys of dict will be returned.
  • values()
    • It returns list of all values present in  given dictionary.
    • dict.values()
    • Above syntax shows that all keys of dict will be returned.
  • items()
    • It is used to find the key – value pairs and return a tuple of same.
    • dict.items()
    • Above syntax shows that all key:value pairs of dict will be returned.
  • pop()
    • It is used to remove specified key and return the corresponding value.
    •  If key is not found, d is returned if given, otherwise KeyError is raised
    • dict.pop('key')

       

  • popitem()
    • It is used to remove key value pair from given dictionary without mentioning key or value as parameter.
    • popitem() does not have any parameter.
    • dict.popitem()

Example of dictionary methods and opertaions:

dictionary methods and operations

Output of dictionary methods in python

>>>
sorted itv by using keys [1, 2, 3, 4, 5]
square is {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
after del square[4] {1: 1, 2: 4, 3: 9, 5: 25}
itv after appending itv itv[6]=’six’ {1: ‘one’, 2: ‘two’, 3: ‘three’, 4: ‘four’, 5: ‘five’, 6: ‘six’}
len(itv) 6
itv.get(6) six
itv.items() dict_items([(1, ‘one’), (2, ‘two’), (3, ‘three’), (4, ‘four’), (5, ‘five’), (6, ‘six’)])
itv.values() dict_values([‘one’, ‘two’, ‘three’, ‘four’, ‘five’, ‘six’])
after itv.pop(2) {1: ‘one’, 3: ‘three’, 4: ‘four’, 5: ‘five’, 6: ‘six’}
after itv.popitem() {3: ‘three’, 4: ‘four’, 5: ‘five’, 6: ‘six’}
after itv.clear() {}
>>>
>>>

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