Thursday, November 24, 2016




How do you store & retrieve native Python data objects in file (without using the eval() function)?

We can use the pickle module and its dump() and load() functions to store and retrieve the data objects to and from a file respectively. 

In the code block below we are storing a dictionary object D to a file & reading it back in E.


In 3.5.1

The same works for python 2.x

Note:- Using eval() is considered as a security hole since if used in conjunction with the built-in input() function it can lead to dynamically injected intrusive code that can, for example, wipe out the entire data on your system!



Thursday, November 10, 2016


How to reverse a string in python?


In both python 2.x and 3.x you can use the extended slicing technique to reverse a string.

Note:- The first two bounds of S[::-1] default to 0 and the length of the sequence and a stride of −1 indicates that the slice should go from right to left instead of the usual left to right.


Also note that Strings are immutable sequences. Hence S[::-1] doesn't change S in place, instead it creates a new object as can be seen in both python 2.x and 3.x with the 'is' operator which tests object identity.





Wednesday, November 9, 2016



How do you create a dictionary with keys and values from two different lists?

We can use the zip built-in function to stitch the lists and then pass it to the dict constructor to build a dictionary.


Note that the zip function doesn't return a list in python 3.x instead it returns a zip object reference which can be passed to the list and tuple constructors to create a list and tuple respectively. In python 2.x however, it returns a list.

                  In 3.5.1
               
          In 2.7.12  





Tuesday, November 8, 2016




How to convert a Dictionary into a list and vice-versa in python?

A: If D is a Dictionary in python 3.x we can pass the D.items() dictionary view to the list constructor to convert the dictionary to a list. Below screenshot if from python 3.5.1


Code for python 2.x (below screenshot is from 2.7.12)


You can also create a list by retrieving only the Dictionary values.


Note:- In python 2.x; D.items() returns a list while in 3.x it returns a dictionary view object.
 In 3.5.1                                In 2.7.12
                        

And, of course, the elements of the list are tuples.
              In 3.5.1                                                                 In 2.7.12

Also note that unlike in python 2.x the built-in data types python 3.x are classes.

Now, you can simply use the dict() function to create a dictionary from a list.