Dictionary in Python

Python Dictionary

Python dictionary is a collection of key: value pairs, where each key: value pairs are separated by a comma. In other programming languages it's associative array.


Here is a visualization of dictionary in Python.

{key: value, key1: value1, key2: value2}.

(This is the collection of key: value pairs which is called as dictionary).


Properties of Python dictionary

  • Dictionary is indexed by keys.
    • values in dictionary are accessed by it's key.
  • Keys in dictionary can be any immutable type.
    • i.e. it can be strings, numbers or tuples, nested tuples are also possible.
  • Mutable objects can not be used as keys such as list.
  • Keys are unique within one dictionary.
  • The main operation of dictionary is to store a value with some key and extract or access the value with that key.
  • If try to store a value with a key that already exists, then the older value will be overwritten with the new value.

  • Get a KeyError when try to access a value with a key which not exists in a dictionary.

Initialization of Dictionary

There are two ways for the initialization of dictionary.

  1. With curly brackets '{}'.
  2. Using dict() constructor.

Initialization of Dictionary using curly brackets

The key: value pairs are placed within the curly brackets, for the initialization of dictionary.


Strings as keys.

Program

>>> a = {'one': 1, 'two': 2, 'three': 3}
>>> print(a)
{'one': 1, 'two': 2, 'three': 3}


Numbers as keys.

Program

>>> a = {1: 'one', 2: 'two', 3: 'three'}
>>> print(a)
{1: 'one', 2: 'two', 3: 'three'}


Tuples as keys.

Program

>>> a = {('Maruti', 'Tata'): 'cars',
     (1, 2): 'numbers',
     (3, 5): ('three', 'five')}
>>> print(a)
{('Maruti', 'Tata'): 'cars', (1, 2): 'numbers', (3, 5): ('three', 'five')}


Keys as the mixture of all (string, number, tuple).


Program

>>> a = {'one': 1, 2: 'two', ('Maruti', 'Tata'): 'cars'}
>>> print(a)
{'one': 1, 2: 'two', ('Maruti', 'Tata'): 'cars'}



Initialization of Dictionary with dict() constructor

Each key: value pairs are placed in list/tuple, all these key: value pair objects are placed in one list/tuple and are passed as an argument to the dict() constructor, for the initialization of dictionary.


Format

variable_name = dict([(key, value), (key1, value1), (key2, value2)])


Program

>>> a = dict([[1, 'one'], [2, 'two'], [3, 'three']])
>>> print(a)
{1: 'one', 2: 'two', 3: 'three'}
>>> 
>>> a = dict([(1, 'one'), (2, 'two'), (3, 'three')])
>>> print(a)
{1: 'one', 2: 'two', 3: 'three'}
>>> 
>>> b = dict(([1, 'one'], [2, 'two'], [3, 'three']))
>>> print(b)
{1: 'one', 2: 'two', 3: 'three'}
>>> 
>>> b = dict(((1, 'one'), (2, 'two'), (3, 'three')))
>>> print(b)
{1: 'one', 2: 'two', 3: 'three'}
>>> 


All the formats above with list/tuple yields the same result.

If the keys are simple string then it's easy to pass as keyword arguments.


Program

>>> a = dict(one=1, two=2, string="H!", cars=('Maruti', 'Tata'))
>>> print(a)
{'one': 1, 'two': 2, 'string': 'H!', 'cars': ('Maruti', 'Tata')}


When the key is repeated, while the initialization of dictionary


Then the value associated with the last key of the repeating key will be stored in the dictionary.


Program

>>> a = {1:'one', 2:'two', 1:'three'}
>>> print(a)
{1: 'three', 2: 'two'}
>>> 
>>> b = dict([(1, 'one'), (2, 'two'), (1, 'three'), (1, 'five')])
>>> print(b)
{1: 'five', 2: 'two'}



Accessing value in dictionary

Dictionary is indexed by keys.


So as to access or extract a value from a dictionary use the key associated with that value.


Program

>>> a = {1:'one', 2: 'two', 3: 'three', 4: 'four', 5: 'five'}
>>> a[1]
'one'
>>> a[5]
'five'

If try to access a value with a key, which is not there in the dictionary.

KeyError is raised.

Program

>>> a = {1:'one', 2: 'two', 3: 'three', 4: 'four', 5: 'five'}
>>> a[6]
Traceback (most recent call last):
  File "<pyshell#45>", line 1, in <module>
    a[6]
KeyError: 6


Changing value in dictionary

Specify the key whose value has to be changed, and assign the value.

Program


>>> a = {1:'one', 2: 'two', 3: 'three', 4: 'four', 5: 'five'}
>>> a[1] = 'zero'
>>> print(a)
{1: 'zero', 2: 'two', 3: 'three', 4: 'four', 5: 'five'}



Adding items in dictionary

For adding a new item in a dictionary, new key is defined and a value is assigned to it.

Program


>>> a = {1:'zero', 2: 'two', 3: 'three', 4: 'four', 5: 'five'}
>>> a[6] ='six'
>>> print(a)
{1: 'zero', 2: 'two', 3: 'three', 4: 'four', 5: 'five', 6: 'six'}



Removing items in dictionary

Following are the method through which items are removed.


Remove item with del, in dictionary

Make use of the del keyword and specify the key for the removal of the item in a dictionary.


Removes the item and returns nothing.

Program


>>> a = {1: 'zero', 2: 'two', 3: 'three', 4: 'four', 5: 'five', 6: 'six'}
>>> del a[1]
>>> print(a)
{2: 'two', 3: 'three', 4: 'four', 5: 'five', 6: 'six'}



Dictionary pop() method

The pop() method takes a 'key' as an argument, for the removal of an item from the dictionary.


Removes and returns the value.

Program


>>> print(a)
{2: 'two', 3: 'three', 4: 'four', 5: 'five', 6: 'six'}
>>> a.pop(4)
'four'
>>> print(a)
{2: 'two', 3: 'three', 5: 'five', 6: 'six'}


Dictionary popitem() method

Removes the last item in a dictionary and takes no argument.


Removes and return the (key, value) pairs.

Program


>>> print(a)
{2: 'two', 3: 'three', 5: 'five', 6: 'six'}
>>> a.popitem()
(6, 'six')
>>> print(a)
{2: 'two', 3: 'three', 5: 'five'}



Dictionary clear() method

Empties a dictionary.

Program


>>> print(a)
{2: 'two', 3: 'three', 5: 'five'}
>>> a.clear()
>>> print(a)
{}



Completely removing a dictionary

By using the del keyword and specifying the dictionary name, will completely remove the dictionary from the program.


Dictionary will be deleted.

Program


>>> a = {1:'one', 2: 'two', 3: 'three', 4: 'four', 5: 'five'}
>>> print(a)
{1: 'one', 2: 'two', 3: 'three', 4: 'four', 5: 'five'}
>>> del a
>>> print(a)
Traceback (most recent call last):
  File "<pyshell#71>", line 1, in <module>
    print(a)
NameError: name 'a' is not defined
>>> 



Dictionary length

The len() built-in function returns the number of key: value pairs in a dictionary.


Program


>>> a = {1:'one', 2: 'two', 3: 'three', 4: 'four', 5: 'five'}
>>> len(a)
5



Copy a dictionary

The command 'dictionary1 = dictionary2' will not work because, the changes made in dictionary1 will automatically be made in dictionary2. As both the dictionaries will have the same memory location.

Program


>>> a = {1:'one', 2: 'two', 3: 'three'}
>>> b = a
>>> a[0] = 'zero'
>>> print(a)
{1: 'one', 2: 'two', 3: 'three', 0: 'zero'}
>>> print(b)
{1: 'one', 2: 'two', 3: 'three', 0: 'zero'}
>>> id(a) == id(b)
True


That's why the copy() method is used. 

Program


>>> a = {1:'one', 2: 'two', 3: 'three'}
>>> b = a.copy()
>>> a[0] = 'zero'
>>> print(a)
{1: 'one', 2: 'two', 3: 'three', 0: 'zero'}
>>> print(b)
{1: 'one', 2: 'two', 3: 'three'}



in Operator in dictionary

To check whether a key is present or exist in a dictionary. Use in keyword.


Program


>>> a = {1:'one', 2: 'two', 3: 'three', 4: 'four', 5: 'five'}
>>> 5 in a
True
>>> 'one' in a
False


Nested Dictionary

It's possible to have a dictionary within another dictionary.


Program


>>> Employee = {'name': {'first_name': 'Jethalal',
   'middle_name': 'Champaklal',
   'last_name': 'Gada'},
    'employee_id': 2651968,
    'address': {'Address_':'Gokuldham society',
      'street': 'powder gally',
      'city': 'mumbai',
      'country': 'India'}
    }
>>> print(Employee)
{'name': {'first_name': 'Jethalal', 'middle_name': 'Champaklal', 'last_name': 'Gada'}, 'employee_id': 23122020, 'address': {'Address_': 'Gokuldham society', 'street': 'powder gally', 'city': 'mumbai', 'country': 'India'}}


Accessing nested dictionary

Accessing nested dictionary is same as that of accessing a value in a normal dictionary.

Program

>>> Employee['name']
{'first_name': 'Jethalal', 'middle_name': 'Champaklal', 'last_name': 'Gada'}
>>> Employee['employee_id']
23122020


Accessing particular value in a dictionary

Firstly we have to specify the key associated with the nested dictionary. Which will allow us to access the values of the nested dictionary.


Then give the key whose value we have to extract.


Program


>>> Employee['name']['first_name']
'Jethalal'


Dictionary methods

MethodsMeaning
clear() Removes all the elements from
a dictionary
copy() Returns a copy of specified
dictionary     
fromkeys() Creates a dictionary with the 
specified iterable keys and value
get() Returns the value with specified
key, if not found return the default
items() Returns view object type dict_items
in which key: value pairs are placed 
in tuple and all tuples are put in a list
keys() Returns view object type dict_keys,
which contains all the keys of a dict.
pop() 
Removes the specified key and return
the corresponding value
popitem() 
Removes the last inserted element and
return the (key, value) pairs as a 2-tuple
setdefault() 
Returns the value of the specified key,
if key not found return the default value
update() 
Update the dictionary with the specified
key: value pairs
values() 
Returns view object type dict_values,
which contains all the values of a dict.




Conclusion

Dictionary is the collection of key: value pairs, which are mutable and accessed using key.

No duplicate keys are allowed (no repetitions of keys).

In this we have learned all the methods available with the Python Dictionary.





Previous                          Next

If you have any query, feel free to ask.

Post a Comment

If you have any query, feel free to ask.

Post a Comment (0)