Monday, 27 June 2016

List of List-Python

Today I am sharing a real time issue.
Currently i am working on reporting module. where to print a report of selled product i need to send product list in report file.
so, I am passing that product list like following.

product_list = [['product_1']*4]*4

Here, total sell of product_1 is 16, and in a one row of A4 size paper i want 4 product label.
so, this will give me like following result:
product_list = [['product_1', 'product_1', 'product_1', 'product_1'],
        ['product_1', 'product_1', 'product_1', 'product_1'],
        ['product_1', 'product_1', 'product_1', 'product_1'],
        ['product_1', 'product_1', 'product_1', 'product_1']]

In product_list[0][1] index i need to change 'product_1' to 'product_2'.
so, I wrote following code.

product_list[0][1] = 'product_2'

Here, i expected output is like following:

product_list = [['product_1', 'product_2', 'product_1', 'product_1'],
        ['product_1', 'product_1', 'product_1', 'product_1'],
        ['product_1', 'product_1', 'product_1', 'product_1'],
        ['product_1', 'product_1', 'product_1', 'product_1']]

But i got following result.

product_list = [['product_1', 'product_2', 'product_1', 'product_1'],
        ['product_1', 'product_2', 'product_1', 'product_1'],
        ['product_1', 'product_2', 'product_1', 'product_1'],
        ['product_1', 'product_2', 'product_1', 'product_1']]

Do you see the problem, second element of all the list changed to 'product_2'.
So it means [['product_1']*4]*4 creates a list that contains reference to the same list ['product_1', 'product_2', 'product_1', 'product_1']

To avoid this we can write following code:

n,m = 4,4
product_list = []
for x in xrange(n):
product_list.append(['product_1'] * m)
print product_list
o/p : [['product_1', 'product_1', 'product_1', 'product_1'],
       ['product_1', 'product_1', 'product_1', 'product_1'],
       ['product_1', 'product_1', 'product_1', 'product_1'],
       ['product_1', 'product_1', 'product_1', 'product_1']]

product_list[0][1] = 'product_2'
print "After Update : ",product_list
After Update : [['product_1', 'product_2', 'product_1', 'product_1'],
               ['product_1', 'product_1', 'product_1', 'product_1'],
               ['product_1', 'product_1', 'product_1', 'product_1'],
               ['product_1', 'product_1', 'product_1', 'product_1']]

Thursday, 23 June 2016

Group dictionary key values in python

Here is a tutorial for group list of dictionary by dictionary key values.

First you needs to sort your list of dictionaries.

For Ex.
animals = [{'name': 'cow', 'size': 'large'},
           {'name': 'bird', 'size': 'small'},
           {'name': 'fish', 'size': 'small'},
           {'name': 'rabbit', 'size': 'medium'},
           {'name': 'pony', 'size': 'large'},
           {'name': 'squirrel', 'size': 'medium'},
           {'name': 'fox', 'size': 'medium'}] 

Here is my list of dictionary.
To sort lits of dictionary you can use following code.

import itertools
from operator import itemgetter
sorted_animals = sorted(animals, key=itemgetter('size'))

Then use following code to group your list of dictionary.

for key, group in itertools.groupby(sorted_animals, key=lambda x:x['size']):
    print key,
    print list(group)

After you will get following result.

large [{'name': 'cow', 'size': 'large'},
       {'name': 'pony', 'size': 'large'}]
medium [{'name': 'rabbit', 'size': 'medium'},
        {'name': 'squirrel', 'size': 'medium'},
        {'name': 'fox', 'size': 'medium'}]
small [{'name': 'bird', 'size': 'small'},
       {'name': 'fish', 'size': 'small'}]

Enjoy, Your list of dictionary is group by dictionary key values.

Generate Random String-Python

Today I am sharing a small piece of Python code to generate random string that i have wrote when i was just started Python Programming. The string will have only the characters: 0-9, A-Z, a-z.


import random
random_word = ''
for i in range(len_of_word):
    random_word += random.choice('ABCDPEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz') 
print random_word

Monday, 20 June 2016

Read And Write in JSON file-Python

Here, i am going to demonstrate real life problem.
before some days, one of my friend was gone for an interview in one of the reputed company.
In interview he has given a following problem.

PROBLEM :
Write a program in python which reads a json file containing list of URLs.
Check if any url is non functional.
Save that data to another json file called : output.json

File : input.json
 
{
"url": ["http://www.programminggit.blogspot.in",
          "http://media.caranddriver.com/images/media/638444/porsche-cayman-photo-640546-s-original.jpg",
          "http://static2.consumerreportscdn.org/content/dam/cro/cars/sports/buying_lg_sports_cars.jpg",
          "http://pop.h-cdn.co/assets/cm/15/05/54cb1d27a519c_-_analog-sports-cars-01-1013-de.jpg",
          "http://pop.h-cdn.co/assets/cm/15/05/54cb1d27a519c_-_analog-sports-cars-01-10"]
}


SOLUTION :

import json

data = {}
# read a json file
with open('input.json') as f:
    json_data = json.load(f)
    for key, value in json_data.iteritems():
        data.update({key: []})
        for each_item in value:
        if str(each_item).find('pop') < 0:
            data.get(key).append(each_item)
# write in json file
with open('output.json', 'w') as f:
    json.dump(data, f)


OUTPUT : output.json

{
"url":  ["http://www.programminggit.blogspot.in",
             "http://media.caranddriver.com/images/media/638444/porsche-cayman-photo-640546-s-original.jpg",
              "http://static2.consumerreportscdn.org/content/dam/cro/cars/sports/buying_lg_sports_cars.jpg"]
}

Friday, 17 June 2016

Swap Values-Python

It's a very well known program given to the beginners, 'swap values of two variables'. In our first introductory programming course (structured programming in C) we solved it in different ways. Most of us used another temporary variable. Some of us did some math tricks. I remember that when i was beginner in programming of C i wrote the following code:

int a, b;
scanf("%d %d", &a, &b);
printf("%d %d\n", b, a);

And it made all other laugh :-D

Here is the best way of doing swapping in python. Try the following code:
a, b = 2,3
print a, b
a, b = b, a
print a, b

- Enjoy. :)