Python Tutorial

Thursday, June 7, 2012

python sort dictionary



Using sorted we can also dictionary data.



d={}
(d['a'],d['o'],d['g'])=("alpha","omega","gamma")

print d
for k in sorted( d.keys() ): 
   print k," ",d[k]

print d



Output:
{'a': 'alpha', 'g': 'gamma', 'o': 'omega'}
a   alpha
g   gamma
o   omega
{'a': 'alpha', 'g': 'gamma', 'o': 'omega'}

python sort tuple



Some example for sort tuple are given



a=[(1,"b"),(2,"a"),(1,"e")]
print a
print sorted(a)

def myTSort(d):
    return d[0] # sort according to first value

print sorted(a,key=myTSort)
print sorted(a,key=myTSort, reverse=True)
print a



Output:
[(1, 'b'), (2, 'a'), (1, 'e')]
[(1, 'b'), (1, 'e'), (2, 'a')]
[(1, 'b'), (1, 'e'), (2, 'a')]
[(2, 'a'), (1, 'b'), (1, 'e')]
[(1, 'b'), (2, 'a'), (1, 'e')]

python string array sort: pass custom function



Sorted is very easy to use. We can use both built-in and custom function for sorting. Some example are given here. Remember it always return a new array by kipping the original array



a=["Life", "is", "very","easy", "with", "python"]

def myFunction(data):
    return data[0]

print sorted(a)
print sorted(a,key=myFunction)
print sorted(a,key=len)
print sorted(a)



Output:
['Life', 'easy', 'is', 'python', 'very', 'with']
['Life', 'easy', 'is', 'python', 'very', 'with']
['is', 'Life', 'very', 'easy', 'with', 'python']
['Life', 'easy', 'is', 'python', 'very', 'with']

python sorted: sort array

I like sorted because it is easy to use, sort multi structered data and also keep the original data which very important some times
 
a=[3,2,1,4,5]
print a
print sorted(a)
print sorted(a,reverse=True)
print a


Output:
[3, 2, 1, 4, 5]
[1, 2, 3, 4, 5]
[5, 4, 3, 2, 1]
[3, 2, 1, 4, 5]

Access shared resource

Sometime we need to access shared document, for example when our application write to a single file on multi-thread. In this case we need to access the through locking.

This technique is useful for web crawler.
lock=threading.Lock()
def writeToFile():
    lock.acquire()
    try:
        //write data
    finally:
        lock.release()

Python Quotes

 
Here some great python quotes. You may share yours
    Perl is worse than Python because people wanted it worse - Larry Wall, Creator of Perl Python fits your brain - Bruce Eckel, Author: Thinking in Java Python is an excellent language & makes sensible compromises. - Peter Norvig. AI Life is better without braces