Skip to main content

Python Sets and Dictionaries

Python Sets

Python Maps examples

A mapping object maps hashable values to arbitrary objects. Mappings are mutable objects. There is currently only one standard mapping type, the dictionary. Dictionaries consist of pairs (called items) of keys and their corresponding values. Dictionaries can be created by placing a comma-separated list of key: value pairs within curly braces Keys are unique within a dictionary while values may not be. The values of a dictionary can be of any type, but the keys must be of an immutable data type such as strings, numbers, or tuples.

Python Set Operations and methods
Python Set methods continueed
>>> SET={'new','old','list','new'}
>>> SET
set(['new', 'old', 'list'])

Lets play with set operations, it is more like school math here...
>>> s={1,2,3,4}
>>> k={3,4,5,6}
>>> len(s)
4
>>> len(k)
4
>>> 1 in s
True
>>> 1 in k
False
>>> 1 not in k
True
>>> s.issubset(k)
False
>>> t={1,2}
>>> t.issubset(s)
True
>>> u=s.union(k)
>>> u
set([1, 2, 3, 4, 5, 6])
>>> i=s.intersection(k)
>>> i
set([3, 4])
>>> t <= s
True
>>> s >= t
True
>>> s|k
set([1, 2, 3, 4, 5, 6])
>>> s&k
set([3, 4])
>>> s-t
set([3, 4])
>>> s^k
set([1, 2, 5, 6])
>>> c=s.copy()
>>> c
set([1, 2, 3, 4])
>>> x=10
>>> x+=1
>>> x
11
>>> s|=k
>>> s
set([1, 2, 3, 4, 5, 6])
>>> s&=k
>>> s
set([3, 4, 5, 6])
>>> s-=t
>>> s
set([3, 4, 5, 6])
>>> s.add(1)
>>> s
set([1, 3, 4, 5, 6])
>>> s.add(2)
>>> s
set([1, 2, 3, 4, 5, 6])
>>> s.pop()
1
>>> s.remove(5)
>>> s
set([2, 3, 4, 6])
>>> s.clear()
>>> s
set([])

The dict : a map/hash data type

Dictionaries are able store set of keys and set of value objects mapping like hashmap

Key- can be any immutable type
Value – can be any standard type or object type

You can define, lookup, view, delete, modify with key-value pairs can be assigned empty object with curly braces {} can be assigned with an elements

Dict methods and fucntions

  • len( dict )
  • dict.copy( )
  • dict.items( )
  • dict.keys( )
  • dict.values( )
  • dict.has_key(‘key’)
  • viewitems( )
  • viewkeys( )
  • viewvalues( )


The builtin dictionary object from the os module, that helps sys-admins this would be the best example.

 os.environ
{'APACHE_HOME': '/bin/httpd.conf', 'SSH_CLIENT': '192.168.1.100 62905 22', 'LOGNAME': 'pavanbsd', 'USER': 'pavanbsd', 'HOME': '/home/pavanbsd', 'PATH': '/usr/lib/jvm/java-7-oracle/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/lib/jvm/java-7-oracle/bin:/usr/lib/jvm/java-7-oracle/db/bin:/usr/lib/jvm/java-7-oracle/jre/bin', 'LANG': 'en_IN', 'TERM': 'xterm', 'SHELL': '/bin/bash', 'XDG_SESSION_COOKIE': '9d869a27940b4997c1ddd3b60000071c-1423259642.573754-89677289', 'LANGUAGE': 'en_IN:en', 'SHLVL': '1', 'JAVA_HOME': '/usr/lib/jvm/java-7-oracle', 'CONFIG_JVM_ARGS': '-Djava.security.egd=file:/dev/./urandom', 'CLASSPATH': '/home/pavanbsd/Oracle/Middleware/Oracle_Home/wlserver/server/lib/weblogic.jar:/home/pavanbsd/Oracle/Middleware/Oracle_Home/wlserver/common/derby/lib/derbytools.jar:/home/pavanbsd/Oracle/Middleware/Oracle_Home/wlserver/common/derby/lib/derbynet.jar:.', 'J2SDKDIR': '/usr/lib/jvm/java-7-oracle', 'WL_HOME': '/home/pavanbsd/Oracle/Middleware/Oracle_Home/wlserver', '_': '/usr/bin/python', 'DERBY_HOME': '/home/pavanbsd/Oracle/Middleware/Oracle_Home/wlserver/common/derby', 'J2REDIR': '/usr/lib/jvm/java-7-oracle/jre', 'SSH_TTY': '/dev/pts/0', 'OLDPWD': '/home/pavanbsd', 'PWD': '/home/pavanbsd/pybin', 'MAIL': '/var/mail/pavanbsd', 'SSH_CONNECTION': '192.168.1.100 62905 192.168.1.105 22'}
>>> d['JAVA_HOME']
'/usr/lib/jvm/java-7-oracle'
>>> d['SHELL']
'/bin/bash'
Lets try something different on dict objects...
Lets create a dictionary and do experiment on all its methods and operations.
>>> d={1:'Pavan',2:'Sudheer',3:'Chakri'}
>>> d
{1: 'Pavan', 2: 'Sudheer', 3: 'Chakri'}
>>> d[1]
'Pavan'
>>> d={1:'Pavan',2:'Sudheer',3:'Chakri'}
>>> d[1]='Vybhava'
>>> d
{1: 'Vybhava', 2: 'Sudheer', 3: 'Chakri'}
>>> len(d)
3
>>> c=d.copy()
>>> c
{1: 'Vybhava', 2: 'Sudheer', 3: 'Chakri'}
>>> c[1]='Pavan'
>>> c
{1: 'Pavan', 2: 'Sudheer', 3: 'Chakri'}
>>> c.keys()
[1, 2, 3]
>>> c.values()
['Pavan', 'Sudheer', 'Chakri']
>>> c.items()
[(1, 'Pavan'), (2, 'Sudheer'), (3, 'Chakri')]
>>> c.items()[1]
(2, 'Sudheer')
>>> c.items()[2]
(3, 'Chakri')
>>> d.has_key(3)
True
>>> d.has_key(4)
False
>>> d.has_key(5)
False
>>> d.viewitems()
dict_items([(1, 'Vybhava'), (2, 'Sudheer'), (3, 'Chakri')])
>>> d.viewkeys()
dict_keys([1, 2, 3])
>>> d.viewvalues()
dict_values(['Vybhava', 'Sudheer', 'Chakri'])
>>> d.get(1)
'Vybhava'

Sample script that illustrates the Python dictionary object types.

dict = {'Language': 'Python', 'Founder': 'Guido Van Rossum'}
print dict
print "Length of dictionary : %d" %  len(dict)
copydict = dict.copy()
print "New Dictionary : %s" %  str(copydict)
print "Items in dictionary: %s" % dict.items()
print "Keys in dictionary: %s" % dict.keys()
print "Vales in Dictionary: %s" % dict.values()
print "Key in dictionary or not: %s" % dict.has_key('Language')
print "Key in dictionary or not: %s" % dict.has_key('Year')
Hope you enjoyed the post, write your valued feedback in the comments.

Comments

Post a Comment

Popular posts from this blog

AWS Auto Scaling using Python Boto3

Auto Scaling Group in AWS configure using Python Boto3  What is Auto Scaling means?  This is key capability or power of Cloud Computing Engineers believe in their skills on scaling abilities.  Amazon EC2 Auto Scaling helps to maintain application availability and lets automatically add or remove EC2 instances using scaling policies that we define.  There are 2 types of scaling policies : Dynamic or predictive. These scaling policies let us add or remove EC2 instances capacity to service established or real-time demand patterns. It contains various steps involved in Auto Scaling process using Python Boto3 we will explore every step that accumulate to form a complete automation solution for a DevOps project. ASG Groups associated with ELB and EC2 instances   Understanding AWS Auto scaling configuration steps Check any running instances Create launch configuration Configure ASG for Auto scaling Verify the configuration Disable Auto Scaling In order to setup A...

Importing modules

What is Python Module? When a Python shell starts it only has access to a basic python functions (“int”, “dict”, “len”, “sum”, “range”, ...) “Modules” that contain additional functionality more methods, more reusability and more sharability. Use “import” keyword to tell the Python shell to load a module. import os, sys Namespaces are one honking great idea -- let's do more of those! (Zen of Python) import this Why importing modules in Python? The major advantage comes when you split your program into several files for easier maintenance. How to import modules in Python A module can be imported by another program to make use of its functionality. This is how we can use the Python standard library as well You can import multiple modules. import module1[, module2[,... moduleN] Normally after module import we can use its containing functions by calling them with refering with the module name followed by period or dot(.) and the function/procedure name. import...