Python

Python Programming – Set

In this Page, We are Providing Python Programming – Set. Students can visit for more Detail and Explanation of Python Handwritten Notes Pdf.

Python Programming – Set

Set

A set is an unordered collection with no duplicate elements. Basic uses include membership testing, eliminating duplicate entries from sequence, mathematical operations like union, intersection, difference, symmetric difference etc. As mentioned in chapter 2, sets are of two types: set (mutable set) and frozenset (immutable set).

>>> a=set ( [ ’ spam ’ , ' eggs ' , 100 , 1234 ] ) 
>>> a
set ( [ ' eggs ' , 100 , 1234 , ' spam ' ] ) 
>>> a=set ( ' abracadabra ' )
>>> a
set ( [ ' a ' , ' r ' , ' b ' , ' c ' , ' d ' ] )
>>> a-frozenset ( [ ' spain ' , ' eggs ' , 100 , 1234 ] ) 
>>> a
frozenset ( [ ' eggs ' , 100 , 1234 , ' spam ' ] )

Being an unordered collection, sets do not record element position or order of insertion. Accordingly, sets do not support indexing, slicing, or other sequence-like behavior.

Set creation

A set can be created in many ways.

Using curly braces

Non-empty set (not frozenset) can be created by placing a comma-separated list of elements within braces. Curly braces cannot be used to create an empty set, because it will create an empty dictionary that will be discussed in the next section.

>>> { ' spam ' , ' eggs ' , 100 , 1234 } 
set ( [ 1234 , 100 , ' eggs ' , ' spam ' ] )

Set comprehension

Python also supports set comprehension:

>>> a= { x for x in ' abracadabra ' if x not in ' abc ' }
>>> a
set ( [ ' r ' , ' d ' ] )

Using built-in function

The built-in functions set ( ) and frozenset ( ) are used to create set and frozenset, respectively, whose elements are taken from iterable. If iterable is not specified, a new empty set is returned.

>>> a=set ( ( ' spam ' , ' eggs ' , 100 , 1234 ) )
>>> a
set ( [ ' eggs ' , 100 , 1234 , ' spam ' ] )
>>> set ( )
set ( [ ] ) 
>>> a=frozenset ( ( ' spam ' , ' eggs ' , 100 , 1234 ) )
>>> a
frozenset ( [ ' eggs ' , 100 , 1234 , ' spam ' ] )
>>> frozenset ( ) 
frozenset ( [ ] ) 
>>> set ( ' abc ' )==frozenset ( ' abc ' )
True

Deleting set

To explicitly remove an entire set, just use the del statement.

>>> ss=set ( ' abracadabra ' )
>>> ss
set ( [ ' a ' , ' r ' , ' b ' , ' c ' , ' d ' ] )
>>> del SS 
>>> SS
Traceback ( most recent call last ) :
File "<stdin>", line 1 , in <module>
NameError: name ' ss ' is not defined

Looping techniques

It is also possible to iterate over each element of a set. However, since set is unordered, it is not known which order the iteration will follow.

>>> ss=set ( ' abracadabra ' )
>>> ss
set ( [ ' a ' , ' r ' , ' b ' , ' c ' , ' d ' ] ) 
>>> for item in ss:
. . . print item
a
r
b
c
d

Membership operation

Set also support membership operation.

>>> a=set ( ' abracadabra ' )
>>> a
set ( [ ' a ' , " r ' r ' b ' , ' c ' , ' d ' ] )
>>> ' r ' in a 
True 
>>> ' rrr ' not in a 
True 
>>> a=frozenset ( ' abracadabra ' )
>>> a
frozenset ( [ ' a ' , ' r ' , ' b ' , ' c ' , ' d ' ] ) 
>>> ' r ' in a
True
>>> ' rrr ' not in a 
True

Python Programming – Set Read More »

Python Programming – Set Methods

In this Page, We are Providing Python Programming – Set Methods. Students can visit for more Detail and Explanation of Python Handwritten Notes Pdf.

Python Programming – Set Methods

Set methods

Below are the methods of both set and frozenset objects. Note that the non-operator versions of these methods accept any iterable as an argument, while their operator-based counterparts require their arguments to be set (set and frozenset).

isdisjoint ( other )
Return True, if the set has no elements in common with other. Sets are disjoint, if and only if their intersection is the empty set.

>>> s1=set ( [ 5 , 10 , 15 , 20] )
>>> s2=set ( [ 30 , 35 , 40 ] )
>>> s1 . isdisjoint ( s2 )
True 
>>> s1=frozenset ( [ 5 , 10 , 15 , 20 ] )
>>> s2=frozenset ( [ 30 , 35 , 40 ] )
>>> s1 . isdisjoint ( s2 )
True
>>> s1=set ( [ 5 , 10 , 15 , 20 ] )
>>> s2=frozenset ( [30 , 35 , 40 ] ) 
>>> s1 . isdisjoint ( s2 )
True

issubset ( other )
Test whether every element in the set is in other.

>>> s1=set ( [ 5 , 15 ] )
>>> s2=set ( [ 5 , 10 , 15 , 20 ] )
>>> s1 . issubset ( s2 )
True
>>> s1 . issubset ( ( 5 , 10 , 15 , 20 ) )
True
>>> s1=frozenset ( [ 5 , 15 ] )
>>> s2=frozenset ( [ 5 , 10 , 15 , 20 ] )
>>> s1 . issubset ( s2 )
True
>>> s1 . issubset ( ( 5 , 10 , 15 , 20 ) )
True

The operator based version of the the above method is set<=other.

>>> s1=set ( [ 5 , 15 ] )
>>> s2=frozenset ( [ 5 , 10 , 15 , 20 ] )
>>> s1<=s2
True

The operator based version setcother test whether the set is a proper subset of other, that is, set<=other and set!=other.

>>> s1=set ( [ 5 , 15 ] )
>>> s2=frozenset ( [ 5 , 10 , 15 , 20 ] )
>>> s1<s2 
True

issuperset (other).

Test whether every element in other is in the set.

>>> s1=set ( [ 5 , 15 ] )
>>> s2=set ( [ 5 , 10 , 15 , 20 ] ) 
>>> s2 . issuperset ( s1 )
True
>>> s2 . issuperset ( ( 5 , 15 ) )
True
>>> s1=frozenset ( [ 5 , 15 ] )
>>> s2=frozenset ( [ 5 , 10 , 15 , 20 ] )
>>> s2 . issuperset ( s1 )
True
>>> s2 . issuperset ( ( 5 , 15 ) )

The operator based version of the the above method is set >=other.

>>> s1=set ( [ 5 , 15 ] )
>>> s2=frozenset ( [ 5 , 10 , 15 , 20 ] )
>>> s1>=s2 
False

The operator-based version set> another test whether the set is a proper superset of other, that is, set>=other and set! =other.

>>> s1=set ( [ 5 , 15 ] )
>>> s2=frozenset ( [ 5 , 10 , 15 , 20 ] )
>>> s1<s2 
False

union ( other, . . . )

Return a new set with elements from the set and all others.

>>> s1=set ( [ 5 , 15 ] )
>>> s2= [ 15 , 20 , 25 ]
>>> s3=frozenset ( [ 30 , 35 , 40 ] )
>>> s1 . union ( s2 , s3 )
set ( [ 35 , 20 , 5 , 40 , 25 , 30 , 15 ] )

The operator based version of the above method is set | other. . .

>>> s1=set ( [ 5 , 15 ] )
>>> s2=set ( [ 15 , 20 , 25 ] ) 
>>> s3=frozenset ( [ 30 , 35 , 40 ] )
>>> s1 | s2 | s3
set ( [ 35 , 20 , 5 , 40 , 25 , 30 , 15 ] )

intersection ( other , . . .)

Return a new set with elements common to the set and all others .

>>> s1=set ( [ 5 , 10 , 15 ] ) 
>>> s2= [ 15 , 20 , 25 , 10 ]
>>> s3=frozenset ( [ 30 , 15 , 35 , 40 , 10 ] ) 
>>> s4= ( 40 , 50 , 10 , 15 , 20 )
>>> si . intersection ( s2 , s3 , s4 ) 
set ( [ 10 , 15 ] )

The operator based version of the above method is set&other . . .

>>> s1=set ( [ 5 , 10 , 15] )
>>> s2=set ( [ 15 , 20 , 25 , 10 ] )
>>> s3=frozenset ( [ 30 , 15 , 35 , 40 , 10 ] )
>>> s4=frozenset ( [ 40 , 50 , 10 , 15 , 20 ] )
>>> s1&s2&s3&s4 
set ( [ 10 , 15 ] )

difference ( other, . . . )

Return a new set with elements in the set that are not in the others.

>>> s1=set ( [ 5 , 10 , 15 ] )
>>> s2= [ 15 , 20 , 25 , 10 ]
>>> s3=frozenset ( [ 30 , 15 , 35 , 40 , 10 ] )
>>> s4= ( 40 , 50 , 10 , 15 , 20 )
>>> s3.difference ( s1 , s2 , s4 ) 
frozenset ( [ 35 , 30 ] )

The operator based version of the above method is set-other- . . .

>>> s1-set ( [ 5 , 10 , 15 ] )
>>> s2=set ( [ 15 , 20 , 25 , 10 ] )
>>> s3=frozenset ( [ 30 , 15 , 35 , 40 , 10 ] )
>>> s4=frozenset ( [ 40 , 50 , 10 , 15 , 20 ] )
>>> s1 - s2 - s3 - s4 
set ( [ 5 ] )
>>> s3 - s1 - s2 - s4 
frozenpet ( [ 35 , 30 ] )

symmetric_difference ( other )

Return a new set with elements in either the set or other but not both.

>>> s1=set ( [ 5 , 10 , 15 ] )
>>> s2= [ 15 , 20 , 25 , 10 ]
>>> s1 . symmetric_difference ( s2 ) 
set ( [ 25 , 20 , 5 ] )

The operator based version of the the above method is set Aother.

>>> s1=set ( [ 5 , 10 , 15 ] )
>>> s2=frozenset ( [ 15 , 20 , 25 , 10 ] )
>>> s1∧ s2
set ( [ 25 , 20 , 5 ] ) 
>>> s2∧s1
frozenset ( [ 25 , 20 , 5 ] )

copy ( )
Return a copy of the set.

>>> s=set ( [ 5 , 10 , 15 , 20 ] )
>>> a=s.copy ( )
>>> a
set ( [ 10 , 20 , 5 , 15 ] )
>>> s=frozenset ( [ 5 , 10 , 15 , 20] )
>>> a=s.copy ( )
>>> a
frozenset ( [ 10 , 20 , 5 , 15 ] )

The following methods are available for set and do not apply to immutable instances of frozenset.

update ( other , . . . )

Update the set, adding elements from all others.

>>> s1=set ( [ 5 , 15 ] )
>>> s2= ( 15 , 20 , 25 )
>>> s3=frozenset ( [ 30 , 35 , 40] )
>>> s1 . update ( s2 , s3 )
>>> s1
set ( [ 35 , 20 , 5 , 40 , 25 , 30 , 15 ] )

The operator based version of the above method is set | =other | . . .

>>> s1=set ( [ 5 , 15 ] )
>>> s2=set ( [ 15 , 20 , 25 ] )
>>> s3=frozenset ( [ 30 , 35 , 40 ] )
>>> s1|= s2 | s3 
>>> s1
set ( ' [ 35 , 5 , 40 , 15 , 20 , 25 , 30 ] )

intersection_update ( other , . . .)

Update the set, keeping only elements found in it and all others.

>>> s1=set ( [ 5 , 10 , 15 ] )
>>> s2= [ 15 , 20 , 25 , 10 ] 
>>> s3=set ( [ 30 , 15 , 35 , 40 , 10 ] ) 
>>> s4= ( 40 , 50 , 10 , 15 , 20 )
>>> s1 . intersection_update ( s2 , s3 , s4 )
>>> s1
set ( [ 10 , 15 ] )

The operator based version of the the above method is set&=other& . . .

>>> s1=set ( [ 5 , 10 , 15] )
>>> s2=set ( [ 15 , 20 , 25 , 10] )
>>> s3=frozenset ( [ 30 , 15 , 35 , 40 , 10 ] )
>>> s4=frozenset ( [ 40 , 50 , 10 , 15 , 20 ] )
>>> s1&=s2&s3&s4 
>>> s1
set ( [10 , 15 ] )

difference_update(other, . . .)

Update the set, removing elements found in others.

>>> s1=frozenset ( [ 5 , 10 , 15 ] )
>>> s2= [ 15 , 20 , 25 , 10 ]
>>> s3=set ( [ 30 , 15 , 35 , 40 , 10 ] )
>>> s4= ( 40 , 50 , 10 , 15 , 20 )
>>> s3 . difference_update ( s1 , s2 , s4 )
>>> s3
set ( [ 35 , 30 ] )

The operator based version of the above method is set-=other | . . .

>>> s1=frozenset ( [ 5 , 10 , 15 ] )
>>> s2=frozenset ( [ 15 , 20 , 25 , 10 ] )
>>> s3=set ( [ 30 , 15 , 35 , 40 , 10 ] )
>>> s4=frozenset ( [ 40 , 50 , 10 , 15 , 20 ] )
>>> s3-=s1 | s2 | s4 
>>> s3
set ( [ 35 , 30 ] )

symmetric_difference_update(other)
Update the set, keeping only elements found in either set, but not in both.

>>> s1=set ( [ 5 , 10 , 15 ] ) 
>>> s2= [ 15 , 20 , 25 , 10 ]
>>> s1 . symmetric_dif ference_update ( s2 )
>>> s1
set ( [ 25 , 20 , 5 ] )

The operator based version of the the above method is set/’=other.

>>> s1=set ( [ 5 , 10 , 15 ] ) 
>>> s2=frozenset ( [ 15 , 20 , 25 , 10 ] )
>>> s1 A=s2 
>>> s1
set ( [ 25 , 20 , 5 ] )

add ( elem )

The method adds element elem to the set.

>>> s=set ( [ 5 , 10 , 15 , 20 ] )
>>> s.add ( 25 )
>>> s
set ( [ 25 , 10 , 20 , 5 , 15 ] )

remove ( elem )

Remove element elem from the set. Raises KeyError, if elem is not contained in the set.

>>> s=set ( [ 5 , 10 , 15 , 20 ] )
>>> s.remove ( 15 )
>>> s
set ( [ 10 , 20 , 5 ] )
>>> s=set ( [ 5 , 10 , 15 , 20 ] )
>>> s . remove ( 100 )
Traceback ( most recent call last ) :
File " <stdin> " , line 1 , in <module>
KeyError: 100

discard ( elem )

Remove element elem from the set if it is present. It is difference from remove () in a way that it does not raise KeyError if elem is not present in the set.

>>> s=set ( [ 5 , 10 , 15 , 20 ] )
>>> s . discard ( 15 )
>>> s
set ( [ 10 , 20 , 5 ] )
>>> s . discard ( 100 )
>>> s
set ( [ 10 , 20 , 5 ] )

pop ( )

Remove and return an arbitrary element from the set. Raises KeyError, if the set is empty.

>>> s=set ( [ 5 , 10 , 15 , 20] ) 
>>> s . pop ( )
10
>>> s
set ( [ 20 , 5 , 15 ] )
>>> s . pop ( )
20
>>> s
set ( [ 5 , 15 ] )

clear ( )

Remove all elements from the set.

>>> s=set ( [ 5 , 10 , 15 , 20 ] )
>>> s . clear ( )
>>> s 
set ( [ ] )

Python Programming – Set Methods Read More »

Python : How to use if, else and elif in Lambda Functions

Lambda function is the function that is anonymous. This anonymous functions are defined using a lambda keyword.

In this article we are going to  discuss about how to use if , else and elif in a lambda functions.

Syntax of Lambda function:

lambda arguments: expression

So this function can have any number of parameter but have only one expression.That expression should return.

Here is an example how we are using Lambda function:

# lambda.py

cube = lambda x: x * x * x

print(cube(11))

Output:

lambda.py

1331

How to use if-else in Lambda function:

Here we are going to use if-else in Lambda function.

lambda <arguments> : <Return Value if condition is True> if <condition> else <Return Value if condition is False>

Let’s take an example, Create  lambda function to check if the given value is between 11 to 22.

# lamda.py

verify = lambda x: True if (x > 9 and x < 18) else False
print(verify(5))
print(verify(17))
print(verify(21))

Output:

RESTART: C:/Users/HP/Desktop/lambda.py
False
True
False

 Conditional lambda function without if-else in python:

Without using if and else keyword we can still get our result using conditional lambda function.For example,

# lambda.py

verify = lambda x : x > 9 and x < 18
print(verify(5))
print(verify(17))
print(verify(21))

Output:

RESTART: C:/Users/HP/Desktop/lambda.py

False
True
False

So we have seen that we can get our result without using if-else statement.

Using filter() function with the conditional lambda function:

This function get a callback() function and a list of elements. It repeats over each and every elements in list and calls the callback() function on every element. If callback() returns True then it will add in new list .In the end, returns the list of items.

# lambda.py

listA = [12, 28, 23, 17, 9, 29, 50]

listOutput = list(filter(lambda x: x > 9 and x < 20, listA))
print(listOutput)

Output:

RESTART: C:/Users/HP/Desktop/lambda.py
[12, 17]

Here we have used lambda function to filter elements and in the end returns list of elements that lies between 9 to 20.

Using if, elif & else in a lambda function:

We can not always depend on if else in a lambda function,sometime there are some possibilities when we need to check on multiple conditions.We can’t directly use else if in a lambda function. But we can fo the same by using if else & brackets .

Syntax:

lambda <args> : <return Value> if <condition > ( <return value > if <condition> else <return value>)

Lets take an example:

lambda.py

converter = lambda x : x*2 if x < 11 else (x*3 if x < 22 else x)
print(converter(5))
print(converter(24))

Output:

lambda.py

10
24

So, in the above example, 5 * 2 = 10, which is less than 11. So, it gives10 because given condition is true. In the case of 24, condition is false; that is why it returns 24 as .

Conclusion:

So in this article we have seen how to use if , else and elif in a lambda functions.We have also seen how to use conditional statement and use of filter  in lambda function.

Python : How to use if, else and elif in Lambda Functions Read More »

Python Programming – Dictionary

In this Page, We are Providing Python Programming – Dictionary. Students can visit for more Detail and Explanation of Python Handwritten Notes Pdf.

Python Programming – Dictionary

Dictionary

Another useful mutable built-in type is “dictionary”. A dictionary is an unordered group of comma-separated “key: value” pairs enclosed within braces, with the requirement that the keys are unique within a dictionary. The main operation of a dictionary is storing a value corresponding to a given key and extracting the value for that given key. Unlike sequences, which are indexed by a range of numbers, the dictionary is indexed by key (key should be of an immutable type, strings and numbers can always be keys).

Tuples can be used as keys if they contain only strings, numbers, or tuples; if a tuple contains any mutable object either directly or indirectly, it cannot be used as a key. The list cannot be used as keys, since lists are of mutable type. Also, as mentioned previously, Python allows adding a trailing comma after the last item of the dictionary.

>>> a= { ' sape ' : 4139 , ' guido ' : 4127 , ' jack ' : 4098 }
>>> a
{ ' sape ' : 4139 , ' jack ' : 4098 , ' guido ' : 4127 }
>>> a [ ' jack ' ]
4098
>>> a= { ' sape ' : 4139, ' guido ' : 4127, ' jack ' : 4098 , }
>>> a
{ ' sape ' : 4139 , ' jack ' : 4098 , ' guido ' : 4127 }

Dictionary creation

Dictionary can be created in many ways.

Using curly braces

Placing a comma-separated record of key-value pairs within the braces adds initial key-value pairs to the dictionary; this is also the way dictionaries are written as output.

>>> a= { ' sape ' : 4139 , ' guido ' : 4127 , ' jack ' : 4098 }
>>> a 
{ ' sape ' , : 4139 , ' jack ' : 4098 , ' guido ' : 412 7 }

A pair of braces creates an empty dictionary.

>>> a= { }
>>> a 
{ }
>>> type ( a ) 
<type ' dict ' >

Dictionary comprehension

Dictionary comprehension provides a concise way to create a dictionary.

>>> { x : x**2 for x in ( 2 , 4 , 6 ) } 
{ 2 : 4 , 4 : 16 , 6 : 36 }

Using built-in function

Dictionary can also be created using a built-in function diet ( ). Consider the following example using diet (), which returns the same dictionary { ” one ” : 1 , ” two ” : 2 , ” three ” : 3 } :

>>> a=dict ( one=1 , two=2 , three=3 )
>>> b= { ' one ' : 1 , ' two ' : 2 , ' three ' : 3 }
>>> c=dict ( zip ( [ ' one ' , ' two ' , ' three ' ] , [ 1 , 2 , 3 ] ) ) 
>>> d=dict ( [ ( ' two', 2), ( ' one ', 1), ( ' three ', 3) J )
>>> e=dict ( { ' three ' : 3 , ' one ' : 1 , ' two ' : 2 } )
>>> a==b==c==d==e 
True

Accessing dictionary elements

To access a dictionary value, use the key enclosed within the square bracket. A KeyError exception is raised if the key is not present in the dictionary.

>>> a= { ' sape ' : 4139 , ' guido ' : 4127 , ' jack ' : 4098 }
>>> a [ ' guido ' ]
4127

Updating dictionary elements

It is possible to add a new item in a dictionary and can also change the value for a given key.

>>> a= { 'sape ' : 4139 , ' guido ' : 4127 , ' jack ' : 4098 }
>>> a [ ' mike ' ]=2299 # Add new item
>>> a [ ' guido ' ]=1000 # Update existing item
>>> a
{ ' sape ' : 4139 , ' mike ' : 2299 , ' jack ' : 4098 , ' guido ' : 1000 }

It is also possible to update a dictionary with another dictionary using the update ( ) method (discussed later).

Deleting dictionary elements

To remove a dictionary item (key-value pair) or the entire dictionary, one can use the del statement. To remove all items (resulting in an empty dictionary), the clear ( ) method (discussed later) can be used.

>>> a= { ' sape ' : 4139 , ' guido ' : 4127 , ' jack ' : 4098 } 
>>> del a [ ' guido ' ]
>>> a
{ ' sape ' : 4139 , ' jack ' : 4098 }
>>> del a
>>> a
Traceback ( most recent call last ) :
File " <stdin> ", line 1, in <module>
NameError: name ' a ' is not defined

Membership operation

Dictionary support membership operation i.e. checking the existence of a key in the dictionary.

>>> a= { 'sape ' : 4139 , ' guido ' : 4127 , ' jack ' : 4098 }
>>> ' jack ' in a 
True
>>> ' tom ' not in a 
True
>>> 4127 in a 
False

Looping techniques

When looping through the dictionary, the key and corresponding value can be retrieved at the same time using the iteritems ( ) method.

>>> a= { ' sape ' : 4139 , ' guido ' : 4127 , ' jack ' : 4098 }
>>> for k , v in a . iteritems ( ) :
. . . print k , v
sape 4139 
jack 4098 
guido 4127

Python Programming – Dictionary Read More »

Python Programming – Dictionary Methods

In this Page, We are Providing Python Programming – Dictionary Methods. Students can visit for more Detail and Explanation of Python Handwritten Notes Pdf.

Python Programming – Dictionary Methods

Dictionary methods

The following are some dictionary methods supported by Python.

diet . clear ( )
Removes all items from the dictionary.

>>> a= { ' Name ' : ' Zara ' , ' Age ' : 7 }
>>> len ( a )
2 
>>> a . clear ( )
>>> len ( a )
0

diet. copy ( )
Returns a copy of the dictionary.

>>> dict1 = { ' Name ' : ' Zara ' , ' Age ' : 7 ]
>>> dict2=dict1 . copy ( )
>>> dict2
{ ' Age ' : 7 , ' Name ' : ' Zara ' }

diet. fromkeys ( seq [ , value ] )
Create a new dictionary with keys from seq and values set to value (default as None).

>>> seq= ( ' name ' , ' age ' , ' gender ' )
>>> a=dict . fromkeys ( seq )
>>> a 
{ ' gender ' : None , ' age ' : None , ' name ' : None }
>>> a=a.fromkeys ( seq , 10 )
>>> a
{ ' gender ' : 10 , ' age ' : 10 , ' name ' : 10 }

diet . get ( key [ , default ] )
Return the value for the key, if the key is in the dictionary, else default. If the default is not given, the default is None.

>>> a= { ' Name ' : ' Zara ' , ' Age ' : 7 }
>>> a.get ( ' Age ' )
7
>>> a. get ( ' Gender ' , ' Never ' )
' Never '
>>> print a.get ( ' Gender ' )
None

diet.has_key ( key )
Test for the presence of a key in the dictionary. Returns True, if the key is present in the dictionary, otherwise False.

>>> a= { ' Name ' : ' Zara ' , ' Age ' : 7 }
>>> a.has_key ( ' Age ' )
True
>>> a.has_key ( ' Gender ' )
False

diet.items ( )
Returns a list of dictionary’s key-value tuple pairs.

>>> a= { ' Name ' : ' Zara ' , ' Age ' : 7 } 
>>> a . items ( )
[ ( ' age ' , 7 ) , ( ' Name ' , ' Zara ' ) ]

diet.iteritems ( )
Returns an iterator over the dictionary’s key-value pairs.

>>> a= { ' Gender ' : ' Female ' , ' Age 1 : 7 , ' Hair color ' : None , ' Name ' : ' Zara ' } 
>>> for b in a . iteritems ( ) :
. . . print ' { 0 } - - - -{ 1 } ' . format ( b [ 0 ] , b [ 1 ] )
. . .
Gender - - - -Female 
Age - - - - 7 
Hair color- - - - None1
Name- - - - Zara

diet.iterkeys ( )
Returns an iterator over the dictionary’s keys.

>>> a= { 1 Gender 1 : ’ Female ' , ' Age ' : 7 , ' Hair color ' : None , ' Name ' : ' Zara ' }
>>> for b in a.iterkeys ( ) :
. . . print b
. . . 
Gender
Age 
Hair color 
Name

diet.itervalues ( )
Returns an iterator over the dictionary’s values.

>>> a= { 1 Gender ' : ' Female ' , ' Age ' : 7 , ' Hair color ' : None , ' Name ' : ' Zara ' }
>>> for b in a.itervalues ( ) :
. . . print b
. . .
Female
7
None
Zara

diet.keys ( )
Returns list of dictionary keys.

>>> a= { ' Name ' : ' Zara ' , ' Age ' : 7 }
>>> a . keys ( )
[ ' Age ' , ' Name ' ]

diet.pop ( key [ , default ] )
If key is.in the dictionary, remove it and return its value, else return default. If default is not given and key is not in the dictionary, a KeyError is raised.

>>> a= { ' Gender ' : ' Female ' , ' Age ' : 7 , ' Hair color ' : None , ' Name ' : ' Zara ' }
>>> a . pop ( ' Age ' , 15 )
7
>>> a . pop ( ' Age ' , 15 )
15 
>>> a
{ ' Gender ' : ' Female ' , ' Hair color ' : None , ' Name ' : ' Zara ' }

diet. popitem ( )
Remove and return an arbitrary key-value pair from the dictionary. If the dictionary is empty, calling popitem () raises an KeyError exception.

>>> a= { ' Gender ' : ' Female ' , ' Age ' : 7 , ' Hair color ' : None , ' Name ' : ' Zara ' } 
>>> a . popitem ( )
( ' Gender ' , ' Female ' )
>>> a . popitem ( )
( ' Age ' , 7 )
>>> a
{ ' Hair color ' : None , ' Name ' : ' Zara ' }

diet . setdefault ( key [ , default ] )
If key is in the dictionary, return its value. If not, insert key with a value of default and return default. The default defaults to None.

>>> a= { ' Name ' : ' Zara ' , ' Age ' : 7 }
>>> a . setdefault ( ' Age ' , 15 )
7
>>> a . setdefault ( ' Gender ' , ' Female ' )
' Female '
>>> a . setdefault ( ' Hair color ' )
>>> a
{ ' Gender ' : ' Female ' , ' Age ' : 7 , ' Hair color ' : None , ' Name ' : ' Zara ' }

diet.update ( [ other ] )
Update the dictionary with the key-value pairs from other, overwriting existing keys, and returns None. The method accepts either another dictionary object or an iterable of key-value pairs (as tuples or other iterables of length two). If keyword arguments are specified, the dictionary is then updated with those key-value pairs.

>>> dict1= { ' Name ' : ' Zara ' , ' Age ' : 7 }
>>> dict2= { ' Gender ' : ' female ' }
>>> dict1 . update ( dict2 )
>>> dict1 . update ( hair_color= ' black ' , eye_color= ' blue ' )
>>> dict1
{ ' eye_color ' : ' blue ' , ' Gender ' : ' female ' , ' Age ' : 7 , ' Name ' : ' Zara ' , ' hair_color ' : ' black ' }

diet . values ( )
Return list of dictionary values.

>>> a= { ' Name ' : ' Zara ' , ' Age ' : 7 }
>>> a . values ( )
[ 7, ' Zara ' ]

Python Programming – Dictionary Methods Read More »

Python Programming – Simple and Compound Statements

In this Page, We are Providing Python Programming – Simple and Compound Statements. Students can visit for more Detail and Explanation of Python Handwritten Notes Pdf.

Python Programming – Simple and Compound Statements

A statement is a unit of code that the Python interpreter can execute. A script usually contains a sequence of statements.

A namespace is a logical grouping of the objects used within a program. Most namespaces are currently implemented as Python dictionaries. Examples of namespaces are the set of built-in names (containing functions such as abs ( ), and built-in exception names), the global names in a module, and the local names in a function definition.

The important thing to know about namespace is that there is absolutely no relation between names in different namespaces. For instance, the functions ____built-in______.open ( ) and os . open ( ) are distinguished by their namespaces. The following is an example of the local namespace.

>>> def example ( arg ) :
. . .       x=4
. . .       print locals ( )
. . . 
>>> example ( 10 )
{ ' x ' : 4 , ' arg ' : 10 }
>>> example ( ' hello ' )
{ ' x ' : 4 , ' arg ' : ' hello ' }

The function example ( ) has two variables in its local namespace: arg, whose value is passed into the function, and x, which is defined within the function. The locals ( ) built-in function return a dictionary of name-value pairs; the keys of this dictionary are the names of local variables as strings; the values of the dictionary are the actual values of the variables.

Python Programming – Simple and Compound Statements Read More »

Python : How to get Current date and time or timestamp ?

Timestamp is a order of characters or encrypted information point out when a certain event occurred, generally it gives date and time of day, sometimes exact to a small fraction of a second.

Get current timestamp using Python

So here we will show you various methods to find out latest date ,time or timestamp in Python.We will import functions from modules time, calendar and date.

1. Using module time :

The function time, return the time in seconds since the date & time as a floating point number.

#using time module
import time
  
# ts stores the time in seconds
ts = time.time()
  
# print the current timestamp
print(ts)

Output:

RESTART: C:/Users/HP/Desktop/article2.py
1618989907.6277814

 

2. Using module datetime :

The datetime module arranges classes for manipulating dates and times. The function datetime.datetime.now which return number of seconds.

# using datetime module
import datetime;
  
# ct stores current time
ct = datetime.datetime.now()
print("current time:-", ct)
  
# ts store timestamp of current time
ts = ct.timestamp()
print("timestamp:-", ts)

Output:

RESTART: C:/Users/HP/Desktop/article2.py
current time:- 2021-04-21 13:21:06.256878
timestamp:- 1618991466.25687

3. Using module calendar :

We are able to understand timestamp by combining multiple functions by multiple modules.

In this topic we are going to use function calendar.timegm to change tuple showing current time.

# using calendar module
# using time module
import calendar;
import time;
  
# gmt stores current gmtime
gmt = time.gmtime()
print("gmt:-", gmt)
  
# ts stores timestamp
ts = calendar.timegm(gmt)
print("timestamp:-", ts)

Output:

RESTART: C:/Users/HP/Desktop/article2.py
gmt:- time.struct_time(tm_year=2021, tm_mon=4, tm_mday=21, tm_hour=8, tm_min=18, tm_sec=37, tm_wday=2, tm_yday=111, tm_isdst=0)
timestamp:- 1618993117

For Current Date only:

Let assume we do not want complete current timestamp, we  just want  current date only. Then what to do ?

datetime class consists of  2 other classes date & time . We can get date object from a datetime object.

from datetime import datetime 
dateTimeObj = datetime.now() 
dateObj = dateTimeObj.date()
print(dateObj)

Output:

RESTART: C:/Users/HP/Desktop/article2.py
2021-04-21

For current Time only:

So here is the process if you want to know only current time.

As datetime module provides a datetime.time class too. We can get time object from a datetime object i.e.

from datetime import datetime
import time

dateTimeObj = datetime.now()
# get the time object from datetime object
timeObj = dateTimeObj.time()

print(timeObj)

Output:

RESTART: C:/Users/HP/Desktop/article2.py
18:14:51.276231

For Current Timestamp using time.time():

Python gives us a module time & it also  has a function time() that returns the number of seconds.

from datetime import datetime
import time
dateTimeObj = datetime.now()
# get the time object from datetime object
timeObj = dateTimeObj.time()
secondsSinceEpoch = time.time()
timeObj = time.localtime(secondsSinceEpoch)
# get the current timestamp elements from struct_time object i.e.
print('Current TimeStamp is : %d-%d-%d %d:%d:%d' % (
timeObj.tm_mday, timeObj.tm_mon, timeObj.tm_year, timeObj.tm_hour, timeObj.tm_min, timeObj.tm_sec))

Output:

RESTART: C:/Users/HP/Desktop/article2.py
Current TimeStamp is : 21-4-2021 18:37:31

Get Current Timestamp using time.ctime():

Time module has some other function time.ctime() .

from datetime import datetime
import time
def ctime(seconds=None):
 timeStr = time.ctime()
 print('Current Timestamp : ', timeStr)
print(ctime())

Output:

RESTART: C:/Users/HP/Desktop/article2.py
Current Timestamp : Wed Apr 21 18:46:44 2021

Conclusion:

So In this article we have seen multiple ways to find out current Date & Time or Timestamp.We have also seen how to use ct.time() and time.time().

Python : How to get Current date and time or timestamp ? Read More »

Python GUI Programming With Tkinter

What Is A Graphical User Interface (GUI)?

Graphical User Interface (GUI) is nothing but a desktop application which helps you to interact with the computers. They perform different tasks in the desktops, laptops and other electronic devices.

  • GUI apps like Text-Editors create, read, update and delete different types of files.
  • Apps like Sudoku, Chess and Solitaire are games which you can play.
  • GUI apps like Google Chrome, Firefox and Microsoft Edge browse through the Internet.

They are some different types of GUI apps which we daily use on the laptops or desktops. We are going to learn how to create those type of apps.

Python offers multiple options for developing GUI (Graphical User Interface). Out of all the GUI methods, tkinter is the most commonly used method. It is a standard Python interface to the Tk GUI toolkit shipped with Python. Python with tkinter is the fastest and easiest way to create the GUI applications. Creating a GUI using tkinter is an easy task.

What Is Tkinter?

Tkinter is actually an inbuilt Python module used to create simple GUI apps. It is the most commonly used module for GUI apps in the Python.

You don’t need to worry about installation of the Tkinter module as it comes with Python default.

To create a tkinter app:

  1. Importing the module – tkinter
  2. Create the main window (container)
  3. Add any number of widgets to the main window
  4. Apply the event Trigger on the widgets.

Importing tkinter is same as importing any other module in the Python code. Note that the name of the module in Python 2.x is ‘Tkinter’ and in Python 3.x it is ‘tkinter’.

import tkinter

There are two main methods used which the user needs to remember while creating the Python application with GUI.

1.Tk(screenName=None,  baseName=None,  className=’Tk’,  useTk=1):

To create a main window, tkinter offers a method ‘Tk(screenName=None,  baseName=None,  className=’Tk’,  useTk=1)’. To change the name of the window, you can change the className to the desired one. The basic code used to create the main window of the application is:

m=tkinter.Tk() where m is the name of the main window object

2.mainloop():

There is a method known by the name mainloop() is used when your application is ready to run. mainloop() is an infinite loop used to run the application, wait for an event to occur and process the event as long as the window is not closed.

m.mainloop()

Python-GUI-Programming-With-Tkinter_mainloop
Output:

 Python-GUI-Programming-With-Tkinter_mainloop-output

tkinter also offers access to the geometric configuration of the widgets which can organize the widgets in the parent windows. There are mainly three geometry manager classes class.

  1. pack() method:It organizes the widgets in blocks before placing in the parent widget.
  2. grid() method:It organizes the widgets in grid (table-like structure) before placing in the parent widget.
  3. place() method:It organizes the widgets by placing them on specific positions directed by the programmer.

There are a number of widgets which you can put in your tkinter application. Some of the major widgets are explained below:

1.Button:

To add a button in your application, this widget is used.
The general syntax is:

w=Button(master, option=value)

master is the parameter used to represent the parent window.
There are number of options which are used to change the format of the Buttons. Number of options can be passed as parameters separated by commas. Some of them are listed below.

  • activebackground: to set the background color when button is under the cursor.
  • activeforeground: to set the foreground color when button is under the cursor.
  • bg: to set he normal background color.
  • command: to call a function.
  • font: to set the font on the button label.
  • image: to set the image on the button.
  • width: to set the width of the button.
  • height: to set the height of the button.

Python-GUI-Programming-With-Tkinter_using-button
Output:

Python-GUI-Programming-With-Tkinter_using-button-output
2.Canvas:

It is used to draw pictures and other complex layout like graphics, text and widgets.
The general syntax is:

w = Canvas(master, option=value)
master is the parameter used to represent the parent window.

There are number of options which are used to change the format of the widget. Number of options can be passed as parameters separated by commas. Some of them are listed below.

  • bd: to set the border width in pixels.
  • bg: to set the normal background color.
  • cursor: to set the cursor used in the canvas.
  • highlightcolor: to set the color shown in the focus highlight.
  • width: to set the width of the widget.
  • height: to set the height of the widget.

 Python-GUI-Programming-With-Tkinter_using-canvas
Output:

 Python-GUI-Programming-With-Tkinter_canvas-output
3.CheckButton:

To select any number of options by displaying a number of options to a user as toggle buttons. The general syntax is:

w = CheckButton(master, option=value)

There are number of options which are used to change the format of this widget. Number of options can be passed as parameters separated by commas. Some of them are listed below.

  • Title: To set the title of the widget.
  • activebackground: to set the background color when widget is under the cursor.
  • activeforeground: to set the foreground color when widget is under the cursor.
  • bg: to set he normal backgrouSteganographyBreakSecret Code:Attach a File:nd color.
  • command: to call a function.
  • font: to set the font on the button label.
  • image: to set the image on the widget.

 Python-GUI-Programming-With-Tkinter_checkbutton.
Output:

Python-GUI-Programming-With-Tkinter_checkbutton-output
4.Entry:

It is used to input the single line text entry from the user.. For multi-line text input, Text widget is used.
The general syntax is:

w=Entry(master, option=value)

master is the parameter used to represent the parent window.
There are number of options which are used to change the format of the widget. Number of options can be passed as parameters separated by commas. Some of them are listed below.

  • bd: to set the border width in pixels.
  • bg: to set the normal background color.
  • cursor: to set the cursor used.
  • command: to call a function.
  • highlightcolor: to set the color shown in the focus highlight.
  • width: to set the width of the button.
  • height: to set the height of the button.

Python-GUI-Programming-With-Tkinter_using-entry
Output:

Python-GUI-Programming-With-Tkinter_using-entry-output
5.Frame:

It acts as a container to hold the widgets. It is used for grouping and organizing the widgets. The general syntax is:

w = Frame(master, option=value)
master is the parameter used to represent the parent window.

There are number of options which are used to change the format of the widget. Number of options can be passed as parameters separated by commas. Some of them are listed below.

  • highlightcolor: To set the color of the focus highlight when widget has to be focused.
  • bd: to set the border width in pixels.
  • bg: to set the normal background color.
  • cursor: to set the cursor used.
  • width: to set the width of the widget.
  • height: to set the height of the widget.

Python-GUI-Programming-With-Tkinter_frame.

Output:

Python-GUI-Programming-With-Tkinter_frame-output
6.Label:

It refers to the display box where you can put any text or image which can be updated any time as per the code.
The general syntax is:

w=Label(master, option=value)
master is the parameter used to represent the parent window.

There are number of options which are used to change the format of the widget. Number of options can be passed as parameters separated by commas. Some of them are listed below.

  • bg: to set he normal background color.
  • bg to set he normal background color.
  • command: to call a function.
  • font: to set the font on the button label.
  • image: to set the image on the button.
  • width: to set the width of the button.
  • height” to set the height of the button.

Python-GUI-Programming-With-Tkinter_label

Output:

 Python-GUI-Programming-With-Tkinter_label-output
7.Listbox:

It offers a list to the user from which the user can accept any number of options.
The general syntax is:

w = Listbox(master, option=value)
master is the parameter used to represent the parent window.

There are number of options which are used to change the format of the widget. Number of options can be passed as parameters separated by commas. Some of them are listed below.

  • highlightcolor: To set the color of the focus highlight when widget has to be focused.
  • bg: to set he normal background color.
  • bd: to set the border width in pixels.
  • font: to set the font on the button label.
  • image: to set the image on the widget.
  • width: to set the width of the widget.
  • height: to set the height of the widget.

 Python-GUI-Programming-With-Tkinter_listbox
Output:

 Python-GUI-Programming-With-Tkinter_listbox-output
8.MenuButton:

It is a part of top-down menu which stays on the window all the time. Every menubutton has its own functionality. The general syntax is:

w = MenuButton(master, option=value)
master is the parameter used to represent the parent window.

There are number of options which are used to change the format of the widget. Number of options can be passed as parameters separated by commas. Some of them are listed below.

  • activebackground: To set the background when mouse is over the widget.
  • activeforeground: To set the foreground when mouse is over the widget.
  • bg: to set he normal background color.
  • bd: to set the size of border around the indicator.
  • cursor: To appear the cursor when the mouse over the menubutton.
  • image: to set the image on the widget.
  • width: to set the width of the widget.
  • height: to set the height of the widget.
  • highlightcolor: To set the color of the focus highlight when widget has to be focused.

9.Menu:

It is used to create all kinds of menus used by the application.
The general syntax is:

w = Menu(master, option=value)
master is the parameter used to represent the parent window.

There are number of options which are used to change the format of this widget. Number of options can be passed as parameters separated by commas. Some of them are listed below.

  • title: To set the title of the widget.
  • activebackground: to set the background color when widget is under the cursor.
  • activeforeground: to set the foreground color when widget is under the cursor.
  • bg: to set he normal background color.
  • command: to call a function.
  • font: to set the font on the button label.
  • image: to set the image on the widget.

from tkinter import *
root = Tk()
menu = Menu(root)
root.config(menu=menu)
filemenu = Menu(menu)
menu.add_cascade(label=’File’, menu=filemenu)
filemenu.add_command(label=’New’)
filemenu.add_command(label=’Open…’)
filemenu.add_separator()
filemenu.add_command(label=’Exit’, command=root.quit)
helpmenu = Menu(menu)
menu.add_cascade(label=’Help’, menu=helpmenu)
helpmenu.add_command(label=’About’)
mainloop()
Output:
Menu output

10.Message:

It refers to the multi-line and non-editable text. It works same as that of Label.
The general syntax is:

w = Message(master, option=value)
master is the parameter used to represent the parent window.

There are number of options which are used to change the format of the widget. Number of options can be passed as parameters separated by commas. Some of them are listed below.

  • bd: to set the border around the indicator.
  • bg: to set he normal background color.
  • font: to set the font on the button label.
  • image: to set the image on the widget.
  • width: to set the width of the widget.
  • height: to set the height of the widget.

 

from tkinter import *
main = Tk()
ourMessage =’This is our Message’
messageVar = Message(main, text = ourMessage)
messageVar.config(bg=’lightgreen’)
messageVar.pack( )
main.mainloop( )
Output:
Python-GUI-Programming-With-Tkinter_message

11.RadioButton:

It is used to offer multi-choice option to the user. It offers several options to the user and the user has to choose one option.
The general syntax is:

w = RadioButton(master, option=value)

There are number of options which are used to change the format of this widget. Number of options can be passed as parameters separated by commas. Some of them are listed below.

  • activebackground: to set the background color when widget is under the cursor.
  • activeforeground: to set the foreground color when widget is under the cursor.
  • bg: to set he normal background color.
  • command: to call a function.
  • font: to set the font on the button label.
  • image: to set the image on the widget.
  • width: to set the width of the label in characters.
  • height: to set the height of the label in characters.
from tkinter import *
root = Tk()
v = IntVar()
Radiobutton(root, text=’GfG’, variable=v, value=1).pack(anchor=W)
Radiobutton(root, text=’MIT’, variable=v, value=2).pack(anchor=W)
mainloop()

Output:

Radiobutton output
12.Scale:

It is used to provide a graphical slider that allows to select any value from that scale. The general syntax is:

w = Scale(master, option=value)
master is the parameter used to represent the parent window.

There are number of options which are used to change the format of the widget. Number of options can be passed as parameters separated by commas. Some of them are listed below.

  • cursor: To change the cursor pattern when the mouse is over the widget.
  • activebackground: To set the background of the widget when mouse is over the widget.
  • bg: to set he normal background color.
  • orient: Set it to HORIZONTAL or VERTICAL according to the requirement.
  • from_: To set the value of one end of the scale range.
  • to: To set the value of the other end of the scale range.
  • image: to set the image on the widget.
  • width: to set the width of the widget.
from tkinter import *
master = Tk()
w = Scale(master, from_=0, to=42)
w.pack()
w = Scale(master, from_=0, to=200, orient=HORIZONTAL)
w.pack()
mainloop()

Output:

Python-GUI-Programming-With-Tkinter_scale
13.Text: 

To edit a multi-line text and format the way it has to be displayed.
The general syntax is:

w  =Text(master, option=value)

There are number of options which are used to change the format of the text. Number of options can be passed as parameters separated by commas. Some of them are listed below.

  • highlightcolor: To set the color of the focus highlight when widget has to be focused.
  • insertbackground: To set the background of the widget.
  • bg: to set he normal background color.
  • font: to set the font on the button label.
  • image: to set the image on the widget.
  • width: to set the width of the widget.
  • height: to set the height of the widget.
from tkinter import *
root = Tk()
T = Text(root, height=2, width=30)
T.pack()
T.insert(END, ‘GeeksforGeeks\nBEST WEBSITE\n’)
mainloop()

Output:

Ttext output
14.TopLevel:

 This widget is directly controlled by the window manager. It don’t need any parent window to work on.The general syntax is:

w = TopLevel(master, option=value)

There are number of options which are used to change the format of the widget. Number of options can be passed as parameters separated by commas. Some of them are listed below.

  • bg: to set he normal background color.
  • bd: to set the size of border around the indicator.
  • cursor: To appear the cursor when the mouse over the menubutton.
  • width: to set the width of the widget.
  • height: to set the height of the widget.

from tkinter import *
root = Tk()
root.title(‘GfG’)
top = Toplevel()
top.title(‘Python’)
top.mainloop()

Output:

Toplevel output

Conclusion:
In this tutorial, you learned how to get started with Python GUI programming. Tkinter is a compelling choice for a Python GUI framework because it’s built into the Python standard library, and it’s relatively painless to make applications with this framework.

Python GUI Programming With Tkinter Read More »

Python: Read a CSV file line by line with or without header

In this article, we will be learning about how to read a CSV file line by line with or without a header. Along with that, we will be learning how to select a specified column while iterating over a file.

Let us take an example where we have a file named students.csv.

Id,Name,Course,City,Session
21,Mark,Python,London,Morning
22,John,Python,Tokyo,Evening
23,Sam,Python,Paris,Morning
32,Shaun,Java,Tokyo,Morning
What we want is to read all the rows of this file line by line.
Note that, we will not be reading this CSV file into lists of lists because that will be very space-consuming and time-consuming. It will also cause problems with the large data. We have to look for a solution that works as an interpreter where we can read a line one at a time so that less memory consumption will take place.
Let’s get started with it!
In python, we have two modules to read the CSV file, one is csv.reader and the second is csv.DictReader. We will use them one by one to read a CSV file line by line.

Read a CSV file line by line using csv.reader

By using the csv.reader module, a reader class object is made through which we can iterate over the lines of a CSV file as a list of values, where each value in the list is a cell value.

Read a CSV file line by line using csv.reader

Code:

from csv import reader
# open file in read mode
with open('students.csv', 'r') as read_obj:
 # pass the file object to reader() to get the reader object
csv_reader = reader(read_obj)
# Iterate over each row in the csv using reader object
for row in csv_reader:
# row variable is a list that represents a row in csv
print(row)
The above code iterated over each row of the CSV file. It fetched the content of each row as a list and printed that generated list.

How did it work?

It performed a few steps:

  1. Opened the students.csv file and created a file object.
  2. In csv.reader() function, the reader object is created and passed.
  3. Now with the reader object, we iterated it by using the for loop so that it can read each row of the csv as a list of values.
  4. At last, we printed this list.

By using this module, only one line will consume memory at a time while iterating through a csv file.

Read csv file without header

What if we want to skip a header and print the files without the header. In the previous example, we printed the values including the header but in this example, we will remove the header and print the values without the header.

Read csv file without header

Code:

from csv import reader
# skip first line i.e. read header first and then iterate over each row od csv as a list
with open('students.csv', 'r') as read_obj:
csv_reader = reader(read_obj)
header = next(csv_reader)
# Check file as empty
if header != None:
# Iterate over each row after the header in the csv
for row in csv_reader:
# row variable is a list that represents a row in csv
print(row)
We can see in the image above, that the header is not printed and the code is designed in such a way that it skipped the header and printed all the other values in a list.

Read csv file line by line using csv module DictReader object

Now, we will see the example using csv.DictReader module. CSV’s module dictReader object class iterates over the lines of a CSV file as a dictionary, which means for each row it returns a dictionary containing the pair of column names and values for that row.

Read csv file line by line using csv module DictReader object

Code:

from csv import DictReader
# open file in read mode
with open('students.csv', 'r') as read_obj:
# pass the file object to DictReader() to get the DictReader object
csv_dict_reader = DictReader(read_obj)
# iterate over each line as a ordered dictionary
for row in csv_dict_reader:
# row variable is a dictionary that represents a row in csv
print(row)
The above code iterated over all the rows of the CSV file. It fetched the content of the row for each row and put it as a dictionary.

How did it work?

It performed a few steps:

  1. Opened the students.csv file and created a file object.
  2. In csv.DictReader() function, the reader object is created and passed.
  3. Now with the reader object, we iterated it by using the for loop so that it can read each row of the csv as a dictionary of values. Where each pair in this dictionary represents contains the column name & column value for that row.

It also saves the memory as only one row at a time is in the memory.

Get column names from the header in the CSV file

We have a member function in the DictReader class that returns the column names of a csv file as a list.

Get column names from the header in the CSV fileCode:

from csv import DictReader
# open file in read mode
with open(‘students.csv’, ‘r’) as read_obj:
# pass the file object to DictReader() to get the DictReader object
csv_dict_reader = DictReader(read_obj)
# get column names from a csv file
column_names = csv_dict_reader.fieldname
print(column_names)

Read specific columns from a csv file while iterating line by line

Read specific columns (by column name) in a CSV file while iterating row by row

We will iterate over all the rows of the CSV file line by line but will print only two columns of each row.
Read specific columns (by column name) in a csv file while iterating row by row
Code:
from csv import DictReader
# iterate over each line as a ordered dictionary and print only few column by column name
withopen('students.csv', 'r')as read_obj:
csv_dict_reader = DictReader(read_obj)
for row in csv_dict_reader:
print(row['Id'], row['Name'])
DictReader returns a dictionary for each line during iteration. As in this dictionary, keys are column names and values are cell values for that column. So, for selecting specific columns in every row, we used column name with the dictionary object.

Read specific columns (by column Number) in a CSV file while iterating row by row

We will iterate over all the rows of the CSV file line by line but will print the contents of the 2nd and 3rd column.

Read specific columns (by column Number) in a csv file while iterating row by row

Code:

from csv import reader
# iterate over each line as a ordered dictionary and print only few column by column Number
with open('students.csv', 'r') as read_obj:
csv_reader = reader(read_obj)
for row in csv_reader:
print(row[1], row[2])
With the csv.reader each row of the csv file is fetched as a list of values, where each value represents a column value. So, selecting the 2nd & 3rd column for each row, select elements at index 1 and 2 from the list.
The complete code:
from csv import reader
from csv import DictReader
def main():
print('*** Read csv file line by line using csv module reader object ***')
print('*** Iterate over each row of a csv file as list using reader object ***')
# open file in read mode
with open('students.csv', 'r') as read_obj:
# pass the file object to reader() to get the reader object
csv_reader = reader(read_obj)
# Iterate over each row in the csv using reader object
for row in csv_reader:
# row variable is a list that represents a row in csv
print(row)
print('*** Read csv line by line without header ***')
# skip first line i.e. read header first and then iterate over each row od csv as a list
with open('students.csv', 'r') as read_obj:
csv_reader = reader(read_obj)
header = next(csv_reader)
# Check file as empty
if header != None:
# Iterate over each row after the header in the csv
for row in csv_reader:
# row variable is a list that represents a row in csv
print(row)
print('Header was: ')
print(header)
print('*** Read csv file line by line using csv module DictReader object ***')
# open file in read mode
with open('students.csv', 'r') as read_obj:
# pass the file object to DictReader() to get the DictReader object
csv_dict_reader = DictReader(read_obj)
# iterate over each line as a ordered dictionary
for row in csv_dict_reader:
# row variable is a dictionary that represents a row in csv
print(row)
print('*** select elements by column name while reading csv file line by line ***')
# open file in read mode
with open('students.csv', 'r') as read_obj:
# pass the file object to DictReader() to get the DictReader object
csv_dict_reader = DictReader(read_obj)
# iterate over each line as a ordered dictionary
for row in csv_dict_reader:
# row variable is a dictionary that represents a row in csv
print(row['Name'], ' is from ' , row['City'] , ' and he is studying ', row['Course'])
print('*** Get column names from header in csv file ***')
# open file in read mode
with open('students.csv', 'r') as read_obj:
# pass the file object to DictReader() to get the DictReader object
csv_dict_reader = DictReader(read_obj)
# get column names from a csv file
column_names = csv_dict_reader.fieldnames
print(column_names)
print('*** Read specific columns from a csv file while iterating line by line ***')
print('*** Read specific columns (by column name) in a csv file while iterating row by row ***')
# iterate over each line as a ordered dictionary and print only few column by column name
with open('students.csv', 'r') as read_obj:
csv_dict_reader = DictReader(read_obj)
for row in csv_dict_reader:
print(row['Id'], row['Name'])
print('*** Read specific columns (by column Number) in a csv file while iterating row by row ***')
# iterate over each line as a ordered dictionary and print only few column by column Number
with open('students.csv', 'r') as read_obj:
csv_reader = reader(read_obj)
for row in csv_reader:
print(row[1], row[2])
if __name__ == '__main__':
main()

I hope you understood this article as well as the code.

Happy reading!

Python: Read a CSV file line by line with or without header Read More »

Python: Get First Value in a Dictionary

Dictionaries are Python’s implementation of an associative array, which is a data structure. A dictionary is made up of a set of key-value pairs. Each key-value pair corresponds to a key and its corresponding value.

A dictionary is defined by enclosing a comma-separated list of key-value pairs in curly braces { }. Each key is separated from its associated value by a colon ‘ :

Examples:

Input :

dictionary = {'This': 100, 'is':200, 'BTechGeeks':300}

Output:

100

Find the first value in a dictionary

There are several ways to find the first value in a dictionary some of them are:

Method #1:Using item() function

The view object is returned by the items() method. The key-value pairs of the dictionary are stored in the view object as tuples in a list. Any changes made to the dictionary will be reflected in the view object.

The dictionary’s item() function returns a view of all dictionary items in the form of a sequence of all key-value pairs. Choose the first key-value pair and the first value from this sequence.

Below is the implementation:

# Given Dictionary
dictionary = {'this': 100, 'is': 200, 'BTechGeeks': 300}
# converting dictionary items to list
dictlist = list(dictionary.items())
# printing the first value of this list
print(dictlist[0][1])

Output:

100

Method #2:Using list() and values() functions

To complete this task, a combination of the methods listed above can be used. In this, we just convert the entire dictionaries values extracted by values() into a list and just access the first values. There is only one thing you should keep in mind when using this, and that is its complexity. It will first convert the entire dictionary to a list by iterating over each item, after which it will extract the first element. The complexity of this method would be O(n).

Below is the implementation:

# Given Dictionary
dictionary = {'this': 100, 'is': 200, 'BTechGeeks': 300}
# converting dictionary values to list
dictlist = list(dictionary.values())
# printing the first value of this list
print(dictlist[0])

Output:

100

Method #3:Using iter() and next() functions

These functions can also be used to complete this task. In this case, we simply use next() to get the first next value, and the iter() function is used to get the iterable conversion of dictionary items. So, if you only need the first value, this method is more efficient. Its complexity would be O(1).

Below is the implementation:

# Given Dictionary
dictionary = {'this': 100, 'is': 200, 'BTechGeeks': 300}
# Get first value of dictionary using iter
firstval = next(iter(dictionary.items()))[1]
# printing the first value
print(firstval)

Output:

100

Retrieve the first N values from a Python dictionary

Using list() + values() +slicing:

Convert the dictionary values into a list.

Retrieve the first n values of the dictionary using slicing.

Below is the implementation:

# Given Dictionary
dictionary = {'this': 100, 'is': 200, 'BTechGeeks': 300}
# Given n
n = 2
# converting dictionary values to list
dictvalues = list(dictionary.values())
# print all values upto n using slicing
print(*dictvalues[:n])

Output:

100 200

Related Programs:

Python: Get First Value in a Dictionary Read More »