Showing posts with label python_dict. Show all posts
Showing posts with label python_dict. Show all posts

Oct 15, 2020

Python lamdba filter


result_dict = {
1: {'site': u'test1.com', 'site_name': u'test1', 'is_https': True},
2: {'site': u'test2.com', 'site_name': u'test2', 'is_https': False}
}
print('-' * 30)
print(result_dict)

print('-' * 30)
https_list = dict(filter(lambda x: x if x[1]['is_https'] else None, result_dict.items()))
non_https_list = dict(filter(lambda x: x if not x[1]['is_https'] else None, result_dict.items()))

print(https_list)
print('-' * 30)
print(non_https_list)

Output:
------------------------------
{1: {'site_name': u'test1', 'site': u'test1.com', 'is_https': True}, 
2: {'site_name': u'test2', 'site': u'test2.com', 'is_https': False}}
------------------------------
{1: {'site_name': u'test1', 'site': u'test1.com', 'is_https': True}}
------------------------------
{2: {'site_name': u'test2', 'site': u'test2.com', 'is_https': False}}

Jan 22, 2019

Python Shallow Vs Deep Copy

import copy

#Shallow Copy
#   copy.copy(x)
#   A shallow copy creates a new object which stores the reference of the original elements.
#   A shallow copy doesn't create a copy of nested objects, instead it just copies the reference of nested objects. 

#Deep Copy
#   copy.deepcopy(x)
#   A deep copy creates a new object and recursively adds the copies of nested objects present in the original elements.


print ' --------- Copy by Ref ------ '
dic1 = {'StudnetId': 'test1', 'Scores': [60,70,80,90,85,45]}
dic2 = dic1

print dic1
print dic2

print 'Updating/Appending score 50'
dic1['Scores'].append(50) #update existing

print dic1 #{'StudnetId': 'test1', 'Scores': [60, 70, 80, 90, 85, 45]}
print dic2 #{'StudnetId': 'test1', 'Scores': [60, 70, 80, 90, 85, 45]}

#Both dic1 & dic2 point to same memory locations
print id(dic1) #46138688
print id(dic2) #46138688

print 'Adding new field Age'
dic1['Age'] = 25

print dic1 #{'Age': 25, 'StudnetId': 'test1', 'Scores': [60, 70, 80, 90, 85, 45, 50]}
print dic2 #{'Age': 25, 'StudnetId': 'test1', 'Scores': [60, 70, 80, 90, 85, 45, 50]}

print ' --------- Shallow Copy ------ '
dic1 = {'StudnetId': 'test1', 'Scores': [60,70,80,90,85,45]}
dic2 = copy.copy(dic1)

print dic1 #{'StudnetId': 'test1', 'Scores': [60, 70, 80, 90, 85, 45]}
print dic2 #{'StudnetId': 'test1', 'Scores': [60, 70, 80, 90, 85, 45]}

print "Memory locations of dic1 & dic2 respectively"
#Both dic1 & dic2 point to different memory location
print id(dic1) #57641696
print id(dic2) #57641840

print 'Updating/Appending score 50'
#Updating the existing will 
dic1['Scores'].append(50) #update existing

#Both dic1 & dic2 point to different memory locations
print dic1 #{'StudnetId': 'test1', 'Scores': [60, 70, 80, 90, 85, 45, 50]}
print dic2 #{'StudnetId': 'test1', 'Scores': [60, 70, 80, 90, 85, 45, 50]}

#Shallow Copy -> Internal data points to the same memory location
print "Memory locations of dic1['Scores'] & dic2['Scores'] respectively"
print id(dic1['Scores']) #52223472
print id(dic2['Scores']) #52223472

print 'Adding new field Age'
dic1['Age'] = 25

print dic1 #{'Age': 25, 'StudnetId': 'test1', 'Scores': [60, 70, 80, 90, 85, 45, 50]}
print dic2 #{'StudnetId': 'test1', 'Scores': [60, 70, 80, 90, 85, 45, 50]}

print ' --------- Deep Copy ------ '
dic1 = {'StudnetId': 'test1', 'Scores': [60,70,80,90,85,45]}
dic2 = copy.deepcopy(dic1)

#Both dic1 & dic2 point to different memory locations
print dic1 #{'StudnetId': 'test1', 'Scores': [60, 70, 80, 90, 85, 45]}
print dic2 #{'StudnetId': 'test1', 'Scores': [60, 70, 80, 90, 85, 45]}

print id(dic1) #54035776
print id(dic2) #54037504

print 'Updating/Appending score 50'
dic1['Scores'].append(50) #update existing

print dic1 #{'StudnetId': 'test1', 'Scores': [60, 70, 80, 90, 85, 45, 50]}
print dic2 #{'StudnetId': 'test1', 'Scores': [60, 70, 80, 90, 85, 45]}

print 'Adding new field Age'
dic1['Age'] = 25

print dic1 #{'Age': 25, 'StudnetId': 'test1', 'Scores': [60, 70, 80, 90, 85, 45, 50]}
print dic2 #{'StudnetId': 'test1', 'Scores': [60, 70, 80, 90, 85, 45]}

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    



Jan 2, 2013

Dict keys and values in Python


Dict in Python consists of Key & Value pairs. This is similar to Hash concept in Perl language.

Keys are unique in Dict, Values are not necessarily unique in nature.


relatives = {"Lisa" : "daughter", "Bart" : "son", "Marge" : "mother", "Homer" : "father", "Santa" : "dog"}


#raw_input(), print for Python 2.X Version 
#input(), print() for Python 3.X Version

for member in sorted(relatives.keys()):
    #print "\n",member
    print("\n",member)

for member in sorted(relatives.values()):

    #print "\n",member
    print("\n",member)


Please refer to other topics on Dict like :
Dict in Python
Dict keys and values in Python


Please refer to other topics on List like :
List in Python
Append to list in Python
Delete the last name from the list in Python
Remove an element from List in Python
Check an element exists in an list in Python
Python Filter Vs Map Vs List Comprehension


Please refer to other topics on File Concepts like :
Print File Content in Python
Print File in Reverse Order in Python


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


Dict Example in Python

Today, we discuss about the Dict concept in Python.

Dict in Python consists of Key & Value pairs. This is similar to Hash concept in Perl language.


Keys are unique in Dict, Values are not necessarily unique in nature.


Let's discuss with an example, let's dive & have fun :



relatives = {"Lisa" : "daughter", "Bart" : "son", "Marge" : "mother", "Homer" : "father", "Santa" : "dog"}


#raw_input(), print for Python 2.X Version 
#input(), print() for Python 3.X Version


#Keys are unique


relatives['Marge'] = "mother";

relatives['marge'] = "mother1";

#'Marge' and 'marge' are different keys


for member in sorted(relatives.keys()):

    print("\n",member, "=>", relatives[member])
#print "\n",member

for member in sorted(relatives.values()):

    print("\n",member)
#print "\n",member

for key, value in relatives.items():
print("\n", key, "=>", value)
#print "\n", key, "=>", value




Please refer to other topics on Dict like :
Dict in Python
Dict keys and values in Python


Please refer to other topics on List like :
List in Python
Append to list in Python
Delete the last name from the list in Python
Remove an element from List in Python
Check an element exists in an list in Python
Python Filter Vs Map Vs List Comprehension


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