Python for beginners- Dictionary Operations

 Dictionary is one of the type of collections in python. It combines variety of data items under a common name.

Syntax be like,

 Name={

              "Membername1":"Value",

              "Membername2":"Value",

               ........................................

              "Membernamen":"Value"

             }

An example is given below...

Eg:

Creating a dictionary named "sunglass"

 sunglass = {

                      "brand": "Suntrack"

                      "model": "Wideangle"

                      "Year " : "2023"

                     }

To print the dictionary, use the below code.

print(sunglass)

It displays the output as follows.

{'brand': 'Suntrack', 'model':'Wideangle','Year':'2023'}

The operations on the dictionary are

  • get()
          This method is used to get a value from dictionary. For getting a value from above example, the              following code is used.
          print(sunglass.get("model")) -This displays Wideangle          
  • keys()
          keys are the members in the dictionary. This method is useful to get the keys in the dictionary.

           sunglass = {"brand": "Suntrack", "model": "Wideangle" , "Year " : "2023" }
           sunglass.keys()
         
           When you execute this, you will get the below output.
            dict_keys(['brand','model','Year'])     
  • values()
           These are the data assigned to the keys. To get the values assigned for the keys, use the below                 code.
           sunglass = {"brand": "Suntrack", "model": "Wideangle", "Year ": "2023"}
           sunglass.values()
           The output is
                 dict_values(['Suntrack','Wideangle','2023'])    
  • copy()
           This method is used to copy a value to another variable. For eg,
            sunglass = {"brand": "Suntrack", "model": "Wideangle" , "Year " : "2023" }
            a=sunglass.copy()
            print(a)
           when you run this code, you get the copied value.
            {'brand': 'Suntrack', 'model':'Wideangle','Year':'2023'}
  • pop()
          This method is used to extract a value from the dictionary.
           sunglass = {"brand": "Suntrack", "model": "Wideangle" , "Year " : "2023" }
           sunglass.pop("Year")
           It gives you the year value as output.
           '2023'
  • clear()

             Do you want to empty the dictionary, use this method.

              sunglass = {"brand":"Suntrack","model": "Wideangle","Year ": "2023"}

              sunglass.clear()
              print(sunglass)

              It clears all the data in the sunglass dictionary. The output is {}

         These are operations performed for Dictionary.


 

How to add a value, remove a value and emptying a list???

 List has many operations to perform. The basic operations like creating a list, changing a value, displaying a list, searching an element in a list and finding length of a variable is explained in part 1.

https://www.blogger.com/blog/post/edit/5251857942821229/7649420483850529537

In part 2, the remaining operations are listed below.

  • Adding a value
  • Removing a value
  • Empty a list
  • Usage of constructor
 The operations are explained below.

  =>Adding a value:  

            This can be achieved by two ways. First one is adding a value in the end of the list. Second one  deals with adding in a specified index.

    Method1:Adding a value in the end of the list:

    colorlist=["Red", "Green", "Yellow" ]
    colorlist.append( "Orange")
    print(colorlist)

    While executing this code, you get the following output.
    [ 'Red', 'Green', 'Yellow', 'Orange' ]

    Method2: Adding an item at a specified index:

    colorlist=["Red", "Green", "Yellow" ]
    colorlist.insert( 1,"Orange")
    print(colorlist)

    The output is
     [ 'Red', 'Orange', 'Green', 'Yellow' ]   

=>Removing a value:

      When you want to delete an item, there are two method.Either ,you can delete the last item or you           can delete a specified item.

      Method1 : Remove last item:
       
      colorlist=["Red", "Green", "Yellow" ]
      colorlist.pop()
     
       It displays the output as : ['Yellow']

      Method2 : Remove a item by specified value:

      colorlist= ["Red" ,"Yellow", "Green"]
      colorlist.remove("Yellow")
      print(colorlist)

      The output is : ['Red' ,' Green' ]
       
       Method3: Remove a item by index value:

       colorlist= ["Red" ,"Yellow", "Green"]
       del colorlist[0]

       it displays [ 'Yellow', 'Green' ]    

  => Empty a list:

        When you want to clear the data in the list, use the following code.

       colorlist = ["Red", "Yellow", "Green"]
       colorlist.clear()
       print(colorlist)
 
       It clears all data in the list and prints [].

 => Usage of constructor:

        Constructor is a simple method to initialize an object. 

         colorlist= list(("Red","Green", "Yellow" ))
         print(colorlist)
     
         The output is   ['Red' ,'Green', 'Yellow']

These are second level of list operations in python.

How to create a list and its operations???

Python collections

    Collection is a set of elements stored in a sequence. In python, there are 4 types of collections.

They are

  • List
  • Tuple
  • Set
  • Dictionary

In the above collections, list has variety of operations to do.

Lists

 List is a collection in python. It can store any type of data. It has variety of operations to perform like creating, displaying, access, add, delete, search and so on.

1.Creating a list

 This is the way of creating a new list in python. Colorlist is the list name. Red,Green,Yellow are the values. 

colorlist=[“Red”,”Green”,”Yellow”]

print(colorlist)

 When you execute this code, you get the following output.

['Red', 'Green' ,'Yellow']

2.Access the list items

  After creating the list, you can access the items. Here,it displays the data in first position. list is always starts from index 0.

colorlist=[“Red”,”Green”,”Yellow”]

print(colorlist[1])

 The output is:

  Green

3.Change the value:

If want to change a particular value in the list, you can assign it with another value. Here, is the code...

colorlist=[“Red”,”Green”,”Yellow”]

colorlist[2]=”Blue”

print(colorlist)

while you execute this code, you can get the following output.

['Red', 'Green', 'Blue']

4.Search an item in the list:

 If you want to find an item in the list, use the below code.

colorlist=[“Red”, “Green”, ”Yellow”]

if “Red” in colorlist:

   print(“ Yes, ‘Red’ is in the colorslist”)

 output is:

 Yes, ‘Red’ is in the colorslist

5.Finding length of the list

To find the length of the list,  use the code given.

colorlist=[“Red”, “Green”, ”Yellow”]

print(len(colorlist))

The output is given below.

3

These are the basic operations performed in the list.


Python program for beginners - String operations.

 String is a collection of characters. It is stored in sequence as an array. Normally a string in python is assigned a value by the following syntax.

Syntax:

String_Variable= " String value "

Eg:

a= " Best wishes"

where, a is a variable that represents string. "Best wishes" is the value assigned to string.

Next, a simple python program to display this string is given below.

a="Best wishes"

print(a)

The Program and its output are like this.


The operations on a string variable are listed here.
  • Extracting a character or set of characters.
  • Finding the total number of characters (Length) in a string
  • Converting upper case to Lowercase and vice versa.
  • Adding two strings
  • Replacing characters
  • Splitting the string into sub string
  • White space removing
The sample code is given as below.
  • Extracting a character or set of characters.
          a="Best Wishes"
          print (a[5:11])
         
          It extracts "Wishes" from String a and displays it on the screen.
  • Finding the total number of characters (Length) in a string
          a="Best Wishes"
          print(Len(a))

         This code gives the output as 11.
  • Converting upper case to Lowercase and vice versa.
          a="best wishes"
          print (a.upper())
          This gives the uppercase of the string a. That will be "BEST WISHES".

          b="WELCOME"
          print (b.lower())

          output is "welcome".
  • Adding two strings
         a="Hi"
         b="Hello"
         print(a+b)

         It gives you  "HiHello" as output.
  • Replacing characters
          a="Good"
          print(a.replace("G","F"))

          This code replaces the "G" to "F". Hence the output is "FOOD"
  • Splitting the string into sub string
          a="Best wishes"
          b=a.split(" ")
          print (b)
    
         split function splits the string based on the white space in the string here. 
         The space is between Best and wishes. So, the output is [ 'Best'  'wishes'] 
  • White space removing
          a=" Welcome "
          print(a.strip())

          This code removes the white space in the beginning and the end. Here, the output is " Welcome".

 These are the basic string operations in python.





Python program to generate fibonacci series

 Maths has some wonderful sequences of numbers. one among that is Fibonacci series.

The logic behind Fibonacci series is very simple. It starts with two numbers 0,1 as the first and second elements. the next number is the sum of the previous two numbers. Likewise ,it goes on until it reaches the number of the elements in the series.

In python, it has following steps.

  • This Fibonacci series program starts with getting the number of elements for the series. 
  • Next, it assigns the values to the first two numbers. 
  • It checks the number of elements is less than zero. If yes means, the number is a negative value. So, it prints a message that enter a positive number.
  • Else if the number of elements is equal to 1, it print the the first number alone.
  • Else, it starts a loop. It prints the first value.
  • It adds the previous two numbers and store it into third variable.
  • It exchanges the value of  second variable to first variable and  the value of third variable to second variable.
  • The Loop repeats until n value is zero.

The program is given below.

"Fibonacci.py"

#Python program to generate fibonacci series

#Getting the number of elements for fibonacci series

n=int(input("enter the number of elements:"))

#Assigning values to start fibonacci series x to 0 and y to 1

x,y=0,1

#Check whether the given number is less than zero

if n<=0:

 print("Enter a positive number")

#Check whether the given number is equal to one

elif n==1:

 print("fibonacci sequence  is",n)

 print(x)

else:

 print("The Fibonacci sequence is:")

 for i in range(n):

  print(x)

  z=x+y

  x=y;

  y=z;


Execute this program in any command prompt. You will  get the following output.

This is the simple python program to generate fibonacci series.