All about Python Dictionary


In this article, you will learn everything about Python dictionaries which is an useful in-built data structure frequently used to handle data.

Dictionaries are unordered mapping for storing items. Each item has key-value pair. Instead of storing objects in ordered sequence, like in List, dictionaries uses key-value pair to store objects. This allow users to quickly search for values without knowing index location.

Properties of Dictionary Keys:

  • Dictionaries are mutable, which means we can change their value without changing their key.
  • More than one entry per key is not allowed. When duplicate keys are encountered, the last assignment is considered.

Empty Dictionary
An empty dictionary can be initialized with two curly braces, like this, {}.

#empty dictionary
dict={}

Dictionary
To initialize dictionary with key-value pairs, the items are separated by commas (,) and key is separated from its value by a colon (:) and the whole thing is enclosed in curly braces {}.

#dictionary with mixed datatypes
dict={'Name':'Harshit', 'Age':20, 'Gender':'Male'}

Accessing Values
Instead of using indexing to access values, dictionary uses keys. Dictionary elements can be accessed using square brackets along with the key to obtain its value.

dict['Age']

OUTPUT: 
20

Modifying Values
As the python dictionaries are mutable, we can overwrite the existing value. To overwrite existing values use the following syntax.

#overwrites Age
dict['Age']=21

Adding Values
We use assignment operator to add new items. If the key is already present, then the existing value gets updated. In case key is not present, a new key-value is added to the dictionary.

#adds new item
dict['Place']='Delhi'

Deleting Elements
To remove individual dictionary element or delete entire dictionary use the keyword del. You can also remove all the entries in the dictionary.

del dict['Name']; # remove entry with key 'Name'
dict.clear();     # remove all entries in dict
del dict;        # delete entire dictionary

Nesting with Dictionaries
Dictionaries are very flexible in the data types they can hold. We can have list or dictionary inside dictionary.

my_friends={'Name':['Rahul', 'Himanshu'],'Age':20, 'Place':'Haryana'}
my_friends['Name'][0]

OUTPUT:
'Rahul'

Lets see an example of dictionary nested inside another dictionary.

capital={1:{'Country':'India', 'State':'Delhi'}, 2:{'Country':'US','State':'Washington'}}

Built-in dictionary function
There are built-in functions in python which can be used

  • This function compare the two dictionaries. This returns 0 if both dictionaries are equal, 1 if dict_1>dict_2 and -1 if dict_1<dict_2.
    Note: This is only supported in Python 2.
cmp(dict_1, dict_2)
  • This gives the total length of dictionary. This will be equal to number of items in the dictionary.
len(dict)
  • This function produces a printable string representation of the dictionary.
str(dict)
  • This function returns the type of value passed. In this case it would return dictionary type.
type(dict)

Additional Dictionary Methods
There are additional methods we can use to call on dictionary. Lets get an introduction to some of them.

  • This returns all the key associated with the dictionary.
dict={'Name':'Harshit', 'Age':20, 'Gender':'Male'}
dict.keys() 

OUTPUT: 
dict_keys(['Name', 'Age', 'Gender'])
  • This returns all the values associated with the dictionary.
dict.values()

OUTPUT: 
dict_values(['Harshit', 20, 'Male'])
  • This return all the key-value pairs associated with the dictionary.
dict.items() 

OUTPUT: 
dict_items([('Name', 'Harshit'), ('Age', 20), ('Gender', 'Male')])
  • This makes the copy of existing dictionary to completely new dictionary.
dict={'Name':'Harshit', 'Age':20, 'Gender':'Male'}
new_dict=dict.copy()

Dictionary Comprehension
Dictionary Comprehension is just a handy and faster way to create dictionary in python in just a single line of code.
Here is an example to append the square of the number to the dictionary.

my_dict = dict()
for num in range(10):
    my_dict[num] = num**3
print(my_dict)

OUTPUT:
{0: 0, 1: 1, 2: 8, 3: 27, 4: 64, 5: 125, 6: 216, 7: 343, 8: 512, 9: 729}

Now, lets recreate the above code using dictionary comprehension.

my_dict={x:x**3 for x in range(10)}
print(my_dict)

OUTPUT:
{0: 0, 1: 1, 2: 8, 3: 27, 4: 64, 5: 125, 6: 216, 7: 343, 8: 512, 9: 729}

Advance Dictionary Modules

  • Counter
    Counter is dictionary subclass which helps us count hashable objects. The elements are stored as dictionary key and their occurrences are stored as values. You can import Counter from collections module.
from collections import Counter
#Counter with lists
numb=[1,2,3,4,5,2,1,3,2,1,2,4,5,2,1,4,1,1]
Counter(numb)

OUTPUT:
Counter({1: 6, 2: 5, 3: 2, 4: 3, 5: 2})
#Counter with Strings
Counter('ashbcddcywqhbaayainaba')

OUTPUT:
Counter({'a': 6,
         'b': 3,
         'c': 2,
         'd': 2,
         'h': 2,
         'i': 1,
         'n': 1,
         'q': 1,
         's': 1,
         'w': 1,
         'y': 2})
#Counter with words in sentence
sen="How many times do I have to tell you how many how many"
words=sen.split()
Counter(words)

OUTPUT:
Counter({'How': 1,
         'I': 1,
         'do': 1,
         'have': 1,
         'how': 2,
         'many': 3,
         'tell': 1,
         'times': 1,
         'to': 1,
         'you': 1})
  • defaultdict
    Defaultdict is a dictionary like object which is present in collections module. It takes first argument as a default datatype for the dictionary.
    A defaultdict will never raise a KeyError. Any key that does not exist gets the value returned by the default factory.
from collections import defaultdict
dic={}
dic['one']

OUTPUT:
NameError                                 Traceback (most recent call last)
<ipython-input-23-0af10b7cadba> in <module>()
----> 1 dic['one']

NameError: name 'dic' is not defined

Now, if we use defaultdict subclass to pass object

dic=defaultdict(object)
dic['one']

OUTPUT:
<object at 0x7fedb070b500>

We can also dictionary initialize with default values using lambda function. It will initialize the dictionary with the value you place when you create dictionary. The following example would take any arguments and return 10.

dict = defaultdict(lambda: 10)
dict['one']

OUTPUT:
10
  • Ordereddict
    An ordereddict is dictionary subclass, present in collections module, that remembers the order in which its contents are added.
from collections import OrderedDict
dict={}

dict['one']=1
dict['two']=2
dict['three']=3

for a,b in dict.items():
    print(a,b)
    
OUTPUT:
one 1
three 3
two 2
dict=OrderedDict()

dict['one']=1
dict['two']=2
dict['three']=3

for a,b in dict.items():
    print(a,b)
    
OUTPUT:
one 1
two 2
three 3

There were mappings and they didn't retain any order as to how you added the key or values to the dictionary. With ordered dictionary, you will retain the order
A regular dictionary only look at its content when testing for equality. But, OrderedDict also considers the order in which the items were added.

dict1 = OrderedDict()
dict1['one'] = 1
dict1['two'] = 2


dict2 = OrderedDict()
dict2['two'] = 2
dict2['one'] = 1

print(dict1==dict2)

OUTPUT:
False

They are not equal because items are added in different order.

With this article at OpenGenus, you must have the complete idea of Dictionary in Python. Enjoy.