Showing posts with label python_map. Show all posts
Showing posts with label python_map. Show all posts

Jun 23, 2018

Learning Dictionary in Python

#!/usr/local/bin/python2.7

'''
#Learning Dictionary in Python
    File name: dict_all_operations.py
    Author: Prabhath Kota
    Date: June 22, 2018
    Python Version: 2.7
'''

'''
Python Dictionaries has key value pairs
They are not ordered
They don't have any index
Keys are unique
A key can be any type of objects, for example, a number, string in Python dictionary
Values can be accessed by using key rather than the index 
We can fetch the values by using key
Case sensitive

[ 'clear', 'copy', 'fromkeys', 'get', 'has_key', 'items', 'iteritems', 'iterkeys', 'itervalues', 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values', 'viewitems', 'viewkeys', 'viewvalues']
'''
from copy import deepcopy
import operator

employees = {1000: {'name': 'Sahasra','country': 'India', 'age': 25}, \
1001: {'name': 'Peter','country': 'US', 'age': 21}, \
1002: {'name': 'John','country': 'US', 'age': 36}, \
1003: {'name': 'Sarayu','country': 'India', 'age': 30},\
1004: {'name': 'Akio','country': 'Japan', 'age': 60}, \
1005: {'name': 'Anand','country': 'India', 'age': 50}, \
1006: {'name': 'Vidya','country': 'India', 'age': 32}, \
1007: {'name': 'Salma','country': 'Bangladesh', 'age': 23},}
print employees

#{1000: {'country': 'India', 'age': 25, 'name': 'Sahasra'}, 1001: {'country': 'US', 'age': 21, 'name': 'Peter'}, 1002: {'country': 'US', 'age': 36, 'name': 'John'}, 1003: {'country': 'India', 'age': 30, 'name': 'Sarayu'}, 1004: {'country': 'Japan', 'age': 60, 'name': 'Akio'}, 1005: {'country': 'India', 'age': 50, 'name': 'Anand'}, 1006: {'country': 'India', 'age': 32, 'name': 'Vidya'}, 1007: {'country': 'Bangladesh', 'age': 23, 'name': 'Salma'}}

print '---------------Dictionary Keys---------------'
print employees.keys() #Get employee Ids
#[1000, 1001, 1002, 1003, 1004, 1005, 1006, 1007]

print '---------------Dictionary Values---------------'
print employees.values()
#[{'country': 'India', 'age': 25, 'name': 'Sahasra'}, {'country': 'US', 'age': 21, 'name': 'Peter'}, {'country': 'US', 'age': 36, 'name': 'John'}, {'country': 'India', 'age': 30, 'name': 'Sarayu'}, {'country': 'Japan', 'age': 60, 'name': 'Akio'}, {'country': 'India', 'age': 50, 'name': 'Anand'}, {'country': 'India', 'age': 32, 'name': 'Vidya'}, {'country': 'Bangladesh', 'age': 23, 'name': 'Salma'}]

print '---------------Dictionary Access---------------'
print employees[1002]
#{'country': 'US', 'age': 36, 'name': 'John'}
employee_obj = employees[1002]
print employee_obj['name']
#John
print employee_obj['country']
#US
print employee_obj['age']
#36
#print employee_obj['salary'] #This will throw error
print employee_obj.get('salary') #Get will return None atleast, but won't throw any error

print '---------------Dictionary Check if key exists---------------'
print 1002 in employees
#True
print 2002 in employees.keys()
#False
print employees.has_key('dept')
#None

print '---------------Dictionary Add/update---------------'
print employees
employees[1008] = {'name': 'Sriya','country': 'India', 'age': 42}

print employees.keys()
#[1008, 1000, 1001, 1002, 1003, 1004, 1005, 1006, 1007]

employees.update({1009: {'name': 'Ahmad','country': 'Bangladesh', 'age': 60}})
print employees.keys()
#[1008, 1009, 1000, 1001, 1002, 1003, 1004, 1005, 1006, 1007]

print '---------------Dictionary Delete entry---------------'
print employees.keys()
#[1008, 1009, 1000, 1001, 1002, 1003, 1004, 1005, 1006, 1007]

del employees[1009]

print employees.keys()
#[1008, 1000, 1001, 1002, 1003, 1004, 1005, 1006, 1007]

print employees[1002]
#{'country': 'US', 'age': 36, 'name': 'John'}

del employees[1002]['age']

print employees[1002]
#{'country': 'US', 'name': 'John'}

print employees[1002].pop('country') #You need to specify key name
#US

print employees[1002]
#{'name': 'John'}

print '---'
print employees[1002].popitem() #It randomly removed any one key
#('name', 'John')

print '---'
print employees[1002]
#{}

print '---'
print len(employees)
#9
del employees[1002]

print len(employees)
#8

print '---------------Dictionary copy by ref---------------'
print employees[1008]['age']
employees_1 = employees
employees[1008]['age'] = 45
print employees[1008]['age']
print employees_1[1008]['age']
#42
#45
#45

print '---------------Dictionary shallow copy---------------'
print employees[1008]['age']
employees_1 = employees.copy()
employees[1008]['age'] = 50
print employees[1008]['age']
print employees_1[1008]['age']
#45
#50
#50

print '---------------Dictionary deep copy---------------'
print employees[1008]['age']
employees_1 = deepcopy(employees)
employees[1008]['age'] = 55
print employees[1008]['age']
print employees_1[1008]['age']
#50
#55
#50

print '---------------Dictionary loop---------------'
for key,val in employees.items():
    print key, ' ----> ', val
for key in employees:
    print key, ' ----> ', employees[key]

#1008  ---->  {'country': 'India', 'age': 55, 'name': 'Sriya'}
#1000  ---->  {'country': 'India', 'age': 25, 'name': 'Sahasra'}
#1001  ---->  {'country': 'US', 'age': 21, 'name': 'Peter'}
#1003  ---->  {'country': 'India', 'age': 30, 'name': 'Sarayu'}
#1004  ---->  {'country': 'Japan', 'age': 60, 'name': 'Akio'}
#1005  ---->  {'country': 'India', 'age': 50, 'name': 'Anand'}
#1006  ---->  {'country': 'India', 'age': 32, 'name': 'Vidya'}
#1007  ---->  {'country': 'Bangladesh', 'age': 23, 'name': 'Salma'}


print '---------------Dictionary sort by key---------------'
for key in sorted(employees):
    print key, ' ----> ', employees[key]

#1000  ---->  {'country': 'India', 'age': 25, 'name': 'Sahasra'}
#1001  ---->  {'country': 'US', 'age': 21, 'name': 'Peter'}
#1003  ---->  {'country': 'India', 'age': 30, 'name': 'Sarayu'}
#1004  ---->  {'country': 'Japan', 'age': 60, 'name': 'Akio'}
#1005  ---->  {'country': 'India', 'age': 50, 'name': 'Anand'}
#1006  ---->  {'country': 'India', 'age': 32, 'name': 'Vidya'}
#1007  ---->  {'country': 'Bangladesh', 'age': 23, 'name': 'Salma'}
#1008  ---->  {'country': 'India', 'age': 55, 'name': 'Sriya'}

print '---------------Dictionary sort by value ---------------'
try:
   #Dictionary of Dictionaries - sort of specific value    
   print sorted(employees.items(), key=lambda(x,y): y['age'])
   #[(1001, {'country': 'US', 'age': 21, 'name': 'Peter'}), (1007, {'country': 'Bangladesh', 'age': 23, 'name': 'Salma'}), (1000, {'country': 'India', 'age': 25, 'name': 'Sahasra'}), (1003, {'country': 'India', 'age': 30, 'name': 'Sarayu'}), (1006, {'country': 'India', 'age': 32, 'name': 'Vidya'}), (1005, {'country': 'India', 'age': 50, 'name': 'Anand'}), (1008, {'country': 'India', 'age': 55, 'name': 'Sriya'}), (1004, {'country': 'Japan', 'age': 60, 'name': 'Akio'})]

   #Based on Value
   x = {1: 2000, 3: 8000, 4: 2500, 2: 9000, 9:10000, 7:9500}
   print x
   #{1: 2000, 2: 9000, 3: 8000, 4: 2500, 7: 9500, 9: 10000}

   sorted_x = sorted(x.items(), key=operator.itemgetter(1))
   print sorted_x
   #[(1, 2000), (4, 2500), (3, 8000), (2, 9000), (7, 9500), (9, 10000)]

   sorted_x = sorted(x.items(), key=lambda(x,y): y)
   print sorted_x
   #[(1, 2000), (4, 2500), (3, 8000), (2, 9000), (7, 9500), (9, 10000)]
except Exception, e:
   print e    



Mar 19, 2013

Python - Filter Vs Map Vs Reduce Vs List Comprehension

Today we discuss about the following topics :
1) Filter
2) Map
3) List Comprehension

Lets discuss with few examples:

Filter :
filter(function, sequence) returns a sequence consisting of those items from the sequence for which function(item) is true

Map :
map(function, sequence) calls function(item) for each of the sequence's items and returns a list of the return values

List Comprehension :
List comprehension in Python provides a clear and concise syntax for creating lists from other lists


filter_test.py
#filter(function, sequence) returns a sequence consisting of those items from the sequence for which function(item) is true
def isPythonFile(list_1):
    if list_1.find(".py") == -1:
        return False
    else:
        return True
 
list_1 = ["1.py","2.pl", "3.zip", "4.py","5.php" ]
py_files = filter(isPythonFile, list_1)   #Function is called for each element of list
 
for item in py_files:
    print("Each item in Filetr :" , item)  


Output:
Each item in Filetr : 1.py
Each item in Filetr : 4.py
  

filter_lambda_test.py
foo = [2, 18, 9, 22, 17, 24, 8, 12, 27]
print("Before Lambda :", list(foo))
print("After  Lambda :", list(filter(lambda x: x % 3 == 0, foo)))


Output:
Before Lambda : [2, 18, 9, 22, 17, 24, 8, 12, 27]
After  Lambda : [18, 9, 24, 12, 27]  


map_test.py
print("Before Map :", list(foo))
print("After  Map :", list(map(lambda x: x * 2 + 10, foo)))  


Output:
Before Map : [2, 18, 9, 22, 17, 24, 8, 12, 27]
After  Map : [14, 46, 28, 54, 44, 58, 26, 34, 64]  


smallest_no_using_reduce_test.py
#how to use if else in lambda

from functools import reduce
ll = [10, 12, 45, 2, 100]
out = reduce(lambda x, y: x  if x < y  else y,  ll)
print(out)

Output:
2

largest_no_using_reduce_test.py
#how to use if else in lambda

from functools import reduce
ll = [10, 12, 45, 2, 100]
out = reduce(lambda x, y:  x  if x > y  else y,  ll)
print(out)

Output:
100

list_comprehension_test1.py
input_arr = [2, 3, 4]
output_arr = [2*i for i in input_arr if i > 2]
print("List Comprehension Test 1 :", output_arr)  

Output:
List Comprehension Test 1 : [6, 8]


list_comprehension_test2.py
input_arr = ['Mother Teresa', 'Abraham Lincoln', 'Nelson Mandela']
output_arr = ['Dear...' + i  for i in input_arr if len(i) > 5]
print("List Comprehension Test 2 :",output_arr)  


Output:
List Comprehension Test 2 : ['Dear...Mother Teresa', 'Dear...Abraham Lincoln', 'Dear...Nelson Mandela']  


list_comprehension_test3.py  (if-else inside list comprehension)
input_arr = [20, 30, 40, 33, 55]
output_arr = [2*i if i%2 == 0 else i for i in input_arr]
print("List Comprehension Test 3 :", output_arr)  

Output:
List Comprehension Test 3 :  [40, 60, 80, 33, 55]


Please refer to Regular Expressions Concepts :
Brief on Regular Expressions
Greedy Operators in Regular Expressions in Perl
Modifiers in Regular Expressions in Perl
Capturing concept in Regular Expressions in Perl
Capture Pre Match ,Post Match, Exact match in Regular Expressions in Perl
Non Capturing Paranthesis in Regular Expressions in Perl
Substitute nth occurance in Regular Expressions in Perl
All Topics in Regular Expressions in Perl


You might also wish to read other topics like :
Python Class and Object Example
Inheritance in Python
Packages in Python
Exceptions in Python
How to remove duplicate lines from a file in Perl
How to remove duplicate lines from a file in Pyhton