Saturday 5 December 2015

Python: Dictionaries

Dictionaries are used to store key-value pairs, these are similar to associative arrays, map in other languages. 
>>> employees={1:{"Hari Krishna", "Gurram"}, 2:{"Prithi", "Nair"}, 3: {"Mohan", "Shekkappa"}}
>>> employees[1]
{'Hari Krishna', 'Gurram'}
>>> 
>>> employees[2]
{'Prithi', 'Nair'}
>>> 
>>> employees[3]
{'Shekkappa', 'Mohan'}


As shown in above example, employees is a dictionary, which maps employee id to their names (first and last names).

Id
Name
1
{"Hari Krishna", "Gurram"}
2
{"Prithi", "Nair"}
3
{"Mohan", "Shekkappa"}

Dictionaries are indexed by keys, keys are immutable types. You can use strings, numbers, any other immutable type as keys. Tuples can be used as keys if they contain only strings, numbers, or tuples.

Building dictionary using dict constructor
class dict(**kwarg)
class dict(mapping, **kwarg)
class dict(iterable, **kwarg)
         Above constructors are used to define a dictionary.

>>> emps=dict([(1, "Pradeep"), (2, "Srinath"), (3, "Thushar")])
>>> emps
{1: 'Pradeep', 2: 'Srinath', 3: 'Thushar'}
>>> a = dict(one=1, two=2, three=3)
>>> a
{'two': 2, 'three': 3, 'one': 1}
>>> b = dict({'three': 3, 'one': 1, 'two': 2})
>>> b
{'two': 2, 'three': 3, 'one': 1}


Get number of items in the dictionary
‘len’ method is used to get number of items in the dictionary.    
>>> employees
{1: {'Hari Krishna', 'Gurram'}, 2: {'Prithi', 'Nair'}, 3: {'Shekkappa', 'Mohan'}}
>>> 
>>> len(employees)
3


Get the value associated with key
D[key] is used to get the value associated with key.

>>> employees[1]
{'Hari Krishna', 'Gurram'}
>>> employees[2]
{'Prithi', 'Nair'}
>>> employees[3]
{'Shekkappa', 'Mohan'}


Throws KeyError, if key is not in dictionary.

>>> employees[5]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 5


Override the value associated with key
d[key] = value
Above statement overrides the value associated with key, if key not exist, it creates new item.    
>>> employees
{1: {'Hari Krishna', 'Gurram'}, 2: {'Prithi', 'Nair'}, 3: {'Shekkappa', 'Mohan'}}
>>> employees[4]={"Ranganath", "Thippisetty"}
>>> employees[1]={"Phalgun", "Garimella"}
>>> 
>>> employees
{1: {'Garimella', 'Phalgun'}, 2: {'Prithi', 'Nair'}, 3: {'Shekkappa', 'Mohan'}, 4: {'Ranganath', 'Thippisetty'}}


Remove an item associated with key
del d[key]
‘del’ statement is used to delete an item associate with key (item means <key, value> pair).    
>>> employees
{1: {'Garimella', 'Phalgun'}, 2: {'Prithi', 'Nair'}, 3: {'Shekkappa', 'Mohan'}, 4: {'Ranganath', 'Thippisetty'}}
>>> del employees[2]
>>> 
>>> employees
{1: {'Garimella', 'Phalgun'}, 3: {'Shekkappa', 'Mohan'}, 4: {'Ranganath', 'Thippisetty'}}


Throws KeyError, if key is not in dictionary.

>>> del employees[2]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 2


Check for key existence
key in d
‘in’ operator return true, if key is in dictionary, else false.

>>> employees
{1: {'Garimella', 'Phalgun'}, 3: {'Shekkappa', 'Mohan'}, 4: {'Ranganath', 'Thippisetty'}}
>>> 
>>> 2 in employees
False
>>> 
>>> 3 in employees
True


Check for key non-existence
key not in d
‘not in’ operator return true, if key not in dictionary, else false.

>>> employees
{1: {'Garimella', 'Phalgun'}, 3: {'Shekkappa', 'Mohan'}, 4: {'Ranganath', 'Thippisetty'}}
>>> 
>>> 2 not in employees
True
>>> 
>>> 3 not in employees
False


Get an iterator over dictionary
iter(d)
‘iter’ function returns an iterator over keys of the dictionary.

>>> for key in iter(employees):
...     print(key, employees[key])
... 
1 {'Garimella', 'Phalgun'}
3 {'Shekkappa', 'Mohan'}
4 {'Ranganath', 'Thippisetty'}


Remove all items from dictionary
‘clear’ function is used to remove all items from dictionary.    
>>> employees
{1: {'Garimella', 'Phalgun'}, 3: {'Shekkappa', 'Mohan'}, 4: {'Ranganath', 'Thippisetty'}}
>>> 
>>> employees.clear()
>>> employees
{}


Copy dictionary
‘copy()’ method is used to get shallow copy of this dictionary.

>>> employees = {1: {'Garimella', 'Phalgun'}, 3: {'Shekkappa', 'Mohan'}, 4: {'Ranganath', 'Thippisetty'}}
>>> employees
{1: {'Garimella', 'Phalgun'}, 3: {'Shekkappa', 'Mohan'}, 4: {'Ranganath', 'Thippisetty'}}
>>> 
>>> emps = employees.copy()
>>> emps
{1: {'Garimella', 'Phalgun'}, 3: {'Shekkappa', 'Mohan'}, 4: {'Ranganath', 'Thippisetty'}}


Create new dictionary from keys of given dictionary
fromkeys(seq[, value])

Create a new dictionary with keys from seq and values set to value.

>>> employees
{1: {'Garimella', 'Phalgun'}, 3: {'Shekkappa', 'Mohan'}, 4: {'Ranganath', 'Thippisetty'}}
>>> emps=employees.fromkeys([1,2,3], "default")
>>> emps
{1: 'default', 2: 'default', 3: 'default'}


Get the value associated with this key
get(key[, default])
‘get’ method is used to get the value associated with given key. If key don’t exist, then it return the default value. If default is not given, it defaults to None, so that this method never raises a KeyError.

>>> employees
{1: {'Garimella', 'Phalgun'}, 3: {'Shekkappa', 'Mohan'}, 4: {'Ranganath', 'Thippisetty'}}
>>> employees.get(1)
{'Garimella', 'Phalgun'}
>>> 
>>> employees.get(5, {"Kiran Kumar", "Darsi"})
{'Kiran Kumar', 'Darsi'}


Get all the items in dictionary
‘items’ method is used to get all the items in the dictionary.

>>> employees.items()
dict_items([(1, {'Garimella', 'Phalgun'}), (3, {'Shekkappa', 'Mohan'}), (4, {'Ranganath', 'Thippisetty'})])


Get all the keys from dictionary
‘keys()’ method is used to get all the keys from dictionary.
>>> employees.keys()
dict_keys([1, 3, 4])


pop(key[, default])
If the key is in dictionary, pop method removes and return the value associated with this key. If key don’t present, it returns the default value. If the default value not specified, it throws KeyError.

>>> employees
{1: {'Garimella', 'Phalgun'}, 3: {'Shekkappa', 'Mohan'}, 4: {'Ranganath', 'Thippisetty'}}
>>> 
>>> employees.pop(1)
{'Garimella', 'Phalgun'}
>>> 
>>> employees.pop(1, {"dummy"})
{'dummy'}
>>> 
>>> employees.pop(1)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 1


Remove arbitrary item from dictionary
‘popitem()’ method is used to remove a random item from dictionary. If dictionary is empty, it throws KeyError.    
>>> employees
{3: {'Shekkappa', 'Mohan'}, 4: {'Ranganath', 'Thippisetty'}}
>>> 
>>> employees.popitem()
(3, {'Shekkappa', 'Mohan'})
>>> 
>>> employees.popitem()
(4, {'Ranganath', 'Thippisetty'})
>>> 
>>> employees.popitem()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'popitem(): dictionary is empty'


setdefault(key[, default])
If the key is in dictionary, setdefault method returns the value associated with it, else set the key to default and return default.    
>>> employees
{}
>>> employees.setdefault(1, {'Shekkappa', 'Mohan'})
{'Shekkappa', 'Mohan'}
>>> 
>>> employees
{1: {'Shekkappa', 'Mohan'}}
>>> 
>>> employees.setdefault(1, {'Garimella', 'Phalgun'})
{'Shekkappa', 'Mohan'}
>>> 
>>> employees
{1: {'Shekkappa', 'Mohan'}}


Update dictionary from other dictionary
update([other])
‘update’ method is used to update the dictionary with the key/value pairs from other, overwriting existing keys.

>>> emps1={1: {'Garimella', 'Phalgun'}, 3: {'Shekkappa', 'Mohan'}, 4: {'Ranganath', 'Thippisetty'}}
>>> emps2={1:{'Hari Krishna', "Gurram"}, 5: {'Sudheer', 'Ganji'}}
>>> 
>>> emps1
{1: {'Garimella', 'Phalgun'}, 3: {'Shekkappa', 'Mohan'}, 4: {'Ranganath', 'Thippisetty'}}
>>> 
>>> emps2
{1: {'Hari Krishna', 'Gurram'}, 5: {'Ganji', 'Sudheer'}}
>>> 
>>> emps1.update(emps2)
>>> 
>>> emps1
{1: {'Hari Krishna', 'Gurram'}, 3: {'Shekkappa', 'Mohan'}, 4: {'Ranganath', 'Thippisetty'}, 5: {'Ganji', 'Sudheer'}}
>>> 
>>> emps2
{1: {'Hari Krishna', 'Gurram'}, 5: {'Ganji', 'Sudheer'}}


Get all values from dictionary
‘values’ method is used to get all the values from dictionary.    
>>> emps1
{1: {'Hari Krishna', 'Gurram'}, 3: {'Shekkappa', 'Mohan'}, 4: {'Ranganath', 'Thippisetty'}, 5: {'Ganji', 'Sudheer'}}
>>> 
>>> emps1.values()
dict_values([{'Hari Krishna', 'Gurram'}, {'Shekkappa', 'Mohan'}, {'Ranganath', 'Thippisetty'}, {'Ganji', 'Sudheer'}])











Previous                                                 Next                                                 Home

No comments:

Post a Comment