Python Data Persistence – for loop with dictionary

Python Data Persistence – for loop with dictionary

Dictionary object is not iterable as it is an unordered collection of k-v pairs. However, its views returned by methods – items () , keys ( ) , and values ( ) – do return iterables. So, it is possible to use for statement with them. The following code snippet displays each state-capital pair in a given dictionary object.

Example

#for-5.py
dict1={'Maharashtra': 'Bombay', 'Andhra Pradesh': 'Hyderabad', 'UP': 'Lucknow', 'MP': 'Bhopal'}
for pair in dict1.items():
print (pair)

Output:

E:\python37>python for-5.py 
('Maharashtra', 'Bombay') 
('Andhra Pradesh1, 'Hyderabad') 
('UP' , 1 Lucknow') 
('MP' , 1 Bhopal')

 E:\python3 7 >

As you can see, each pair happens to be a tuple. You can easily unpack it in two different variables as follows:

Example

#for-6.py
dict1={ ' Maharashtra ' : ' Bombay ' , ' Andhra Pradesh ' : ' Hyderabad ' , ' UP ' : ' Lucknow ' , ' MP ' : ' Bhopal ' }
for k ,v in dict1 . items ( ) :
print ( ' capital of { } is { } .'. format ( k , v ) )

Output:

E:\python37>python for-6.py
capital of Maharashtra is Bombay,
capital of Andhra Pradesh is Hyderabad.
capital of UP is Lucknow.
capital of MP is Bhopal.E:\python37>

The keys( ) and values ( ) methods also return iterables. The keys ( ) view returns a collection of keys. Each key is then used to fetch the corresponding value by get ( ) method of the dictionary object.

Example

#for-7.py
dict1={'Maharashtra': 'Bombay', 'Andhra Pradesh': 'Hyderabad', 'UP': 'Lucknow', 'MP': 'Bhopal'}
for k in dict1.keys ( ) :
state=k
capital=dict1.get(k)
print ( 'capital of { } is
{ } .'. format ( state , capital ) )