15 Things to Know to Master Python Dictionaries

Let’s learn about python dictionaries in detail.

Photo by Victoria Pilipchuk on Unsplash

Python Dictionary:

A dictionary is a collection which is unordered, mutable, and indexed. In Python, dictionaries are written with curly brackets {}, and they havekey:value pair.

Updated in Python version 3.7.
Dictionaries preserve insertion order.


15 Things to Know to Master Python Dictionaries

  1. How to access elements from the dictionary?
  2. Difference between d[key] and d.get()?
  3. Difference between d[key]=value and d.setdefault(key,value)?
  4. How to merge two dictionaries in python?
  5. Differences between popitem() and pop()
  6. Differences between del and clear()
  7. How to check if a key exists in the dictionary or not?
  8. How to find the number of items in the dictionary?
  9. How to convert a dictionary to a list?
  10. How to sort a dictionary based on keys and values?
  11. How to reverse a dictionary?
  12. How does equality operation work in a dictionary?
  13. How to remove the first inserted item and last inserted item in a dictionary?
  14. What is meant by dictionary view object?
  15. What are the data types supported by keys and values in a dictionary?

1. How to access elements from the dictionary?

Dictionary values can be accessed by d[key] or d.get(key).

Dictionaries are indexed by keys. (Other Python data structures like list, tuple, strings are indexed by a range of numbers).

d={'a':1,'b':2,'c':3}
print (d['a'])#Output:1
print (d.get('a'))#Output:1

2. Difference between d[key] and d.get()?

Photo by Author

Example:

d={'a':1,'b':2,'c':3}
#print (d['d'])
#Output:KeyError: 'd'

print (d.get('d'))
#Output:None
print (d.get('d',"Not found"))
#Output:Not found

3. Difference between d[key]=value and d.setdefault(key,value)?

Photo by Author

Example: d[key]=value

d={'a':1,'b':2,'c':3}

d['e']=5
#update the dictionary with key 'e' and value as 5.
print (d)#Output:{'a': 1, 'b': 2, 'c': 3, 'e': 5}
#if key already exists means it will  update the value of key

d['a']=99
print (d)#Output:{'a': 99, 'b': 2, 'c': 3, 'e': 5}

Example :setdefault(key,default)

d={'a':1,'b':2,'c':3}
#If key doesn't exists,insert key with a value of default and return default.
print (d.setdefault('e',5))#Output:5
print (d)
#Output:{'a': 1, 'b': 2, 'c': 3, 'e': 5}

##If key exists, return the value of that key.
print(d.setdefault('a',99))#Output:1
print (d)
#Output:{'a': 1, 'b': 2, 'c': 3, 'e': 5}

#If value is not mentioned,it will defaults to None.
print (d.setdefault('f'))#Output:None
print (d)
#Output:{'a': 1, 'b': 2, 'c': 3, 'e': 5, 'f': None}

Pictorial Representation:

Photo by Author

4. How to merge two dictionaries in python?

Refer to my story of Merging dictionaries.

We can merge two dictionaries using dict.update() method.

update()
update() method is used to merge the second dictionary into the first dictionary. It will update the value of the first dictionary.
It won’t create a new dictionary. It is used for merging two dictionaries.

  • Update() method adds elements to the dictionary if the key is not in that dictionary.
  • If the key is in the dictionary means, it will update the new value.Update() function won’t return any value.

Example:

d1={'a':1,'b':2}
d2={'c':3,'d':4}
d1.update(d2)
print (d1)
#Output:{'a': 1, 'b': 2, 'c': 3, 'd': 4}
#If key already exists means, it will update the value.Last one wins
d1={'a':1,'b':2}
d2={'a':5,'d':4}
d1.update(d2)
print (d1)
#Output:{'a': 5, 'b': 2, 'd': 4}

d1={'a':1,'b':2}
d2={'a':5,'d':4}
d2.update(d1)
print (d2)
#Output:{'a': 1, 'd': 4, 'b': 2}

Pictorial Representation:

Photo by Author

5.Differences between popitem() and pop()

Photo by Author

Example: popitem()

d={'a':1,'b':2,'c':3}
print (d.popitem())#Output:('c', 3)
print (d)#Output:{'a': 1, 'b': 2}

#If dictionary is empty calling popitem() will raise KeyError.
d1={}
print (d1.popitem())
#Output:KeyError: 'popitem(): dictionary is empty'

Example: pop(key,default)

d={'a':1,'b':2,'c':3}
print (d.pop('c'))#Output:3
print (d)#Output:{'a': 1, 'b': 2}

#If key is not in dictionary and default is given
print (d.pop('e',"Not Found"))
#Output:Not Found

#If key is not in dictionary and default is not mentioned.
print (d.pop('f'))
#Output:KeyError: 'f'

6.Differences between del and clear()

Photo by Author

Example:

d={'a':1,'b':2,'c':3}
print (d.clear())#Output:None
print (d)#Output:{}

d1={'a':1,'b':2,'c':3}
del d1
#print (d1)
#Output:NameError: name 'd1' is not defined

d2={'a':1,'b':2,'c':3}
del d2['a']
print (d2)#Output:{'b': 2, 'c': 3}
#If key is not in dictionary raises KeyError.
del d2['e']#Output:KeyError: 'e'

7. How to check if a key exists in the dictionary or not?

Membership Test:

in, not in

in — Returns True if the key is present in the dictionary. Checks only key and not values.

Example:

d={'red': 1, 'blue': 2, 'green': 3}
#Checking whether the particular key is in dictionary or not.
print ('red' in d)#Output:True

if 'yellow' in d:
    print ("True")
else:
    print ("False") #Output:False


print ("yellow" not in d)
#Output:True

8. How to find the number of items in the dictionary?

len(d)-Returns the number of item in the dictionary d

d={'red': 1, 'blue': 2, 'green': 3}
print (len(d))
#Output:3

9. How to convert a dictionary to a list?

list(d)
Return a list of all the keys used in the dictionary d.

list(d.values())
Return a list of all values in the dictionary d

list(d.items())
Return a list of tuples(containing key-value pairs) in the dictionary d.

Example:

d={'red': 1, 'blue': 2, 'green': 3}
#Return a list of keys
print (list(d))
#Output:['red', 'blue', 'green']

#Return a list of values
print (list(d.values()))
#Output:[1, 2, 3]

#Return a list of tuples containing key-value pair
print (list(d.items()))
#Output:[('red', 1), ('blue', 2), ('green', 3)]

10. How to sort a dictionary based on keys and values?

sorted(d)
Returns the sorted list of keys in the dictionary d.

sorted(d.values())
Returns the sorted list of values in the dictionary d.

sorted(d.items())
Returns the sorted list of items(key-value pair)in the dictionary d. Sorted based on keys.

sorted(d.items(),key=itemgetter[1])
Returns the sorted list of items(key-value pair)in the dictionary d. Sorted based on values.

Refer to my story of sorting based on a key parameter

Example:

d={'red': 15, 'blue': 20, 'green': 3}
#Sorting keys alone
print (sorted(d))
#Output:['blue', 'green', 'red']

#Sorting values alone
print  (sorted(d.values()))
#Output:[3, 15, 20]

#Sorting items based on keys
print (sorted(d.items()))
#Output:[('blue', 20), ('green', 3), ('red', 15)]

from operator import itemgetter
#sorting items based on values.
print (sorted(d.items(),key=itemgetter(1)))
#Output:[('green', 3), ('red', 15), ('blue', 20)]

11. How to reverse a dictionary?

Changed in Python 3.7
Dictionaries preserve insertion order. Note that updating a key does not affect the order. Keys added after deletion are inserted at the end. The Dictionary order is guaranteed to be insertion order.

Changed in version 3.8: 
Dictionaries are now reversible.

reversed(d)
Return a reversed iterator over the keys of the dictionary d

reversed(d.values())
Return a reversed iterator over the values of the dictionary d

reversed(d.items())
Return a reversed iterator over the items of the dictionary d

We can convert the iterator to list using list() or we can access using for loop or using the next() method.

Example:

d={'red': 15, 'blue': 20, 'green': 3}
#Reverse the keys alone
rev_k=reversed(d)
print (rev_k)#Output:<dict_reversekeyiterator object at 0x00A4E078>
print (list(rev_k))#Output:['green', 'blue', 'red']

#Reverse the values alone
rev_v=reversed(d.values())
print (rev_v)#Output:<dict_reversevalueiterator object at 0x027F03E8>
print (list(rev_v))#Output:[3, 20, 15]

#Reverse the items(key-value pair)
rev_i=reversed(d.items())
print (rev_i)#Output:<dict_reverseitemiterator object at 0x027F02F8>
print (list(rev_i))#Output:[('green', 3), ('blue', 20), ('red', 15)]

12. How does equality operation work in a dictionary?

Dictionaries compare equal if and only if they have the same (key, value) pairs (regardless of ordering).

Example:

d1={'red': 15, 'blue': 20, 'green': 3}
d2={'blue': 20, 'green': 3,'red': 15}
d3={'red': 15, 'blue': 20}

#Always check for equal key-value pair,regardless of ordering.
print (d1==d2) #Output:True
print (d2==d3) #Output:False

13. How to remove the first inserted item and last inserted item in a dictionary?

In OrderedDict, we can remove first inserted item or last inserted item using popitem()

Ordered dictionaries are just like regular dictionaries but have some extra capabilities relating to ordering operations.

collections.OrderedDict([items])

Returns an instance of a dict subclass, which contains methods for rearranging

popitem(last=True)

In OrderedDict,popitem() returns and removes (key,value) pair.
If last=True, the pairs are returned in LIFO(Last In First Out) order. The last inserted item will be removed and returned.
If last=False, the pairs are returned in FIFO(First In First Out)order. The first inserted item will be removed and returned.

Example:

d1={'red': 15, 'blue': 20, 'green': 3}
from collections import OrderedDict
d2=OrderedDict(d1)
print (d2)#Output:OrderedDict([('red', 15), ('blue', 20), ('green', 3)])

#Removes and returns last inseretd item
print (d2.popitem(last=True))#Output:('green', 3)
print (d2)#Output:OrderedDict([('red', 15), ('blue', 20)])

#Removes and returns first inserted item
print (d2.popitem(last=False))#Output:('red', 15)
print(d2)#Output:OrderedDict([('blue', 20)])

14. What is meant by dictionary view object?

The objects returned by dict.keys(), dict.values() and dict.items() are view objects. They provide a dynamic view on the dictionary’s entries, which means that when the dictionary changes, the view reflects these changes.

Dictionary views can be iterated over to yield their respective data and support membership tests.

dict.keys()
Return a new view of the dictionary’s keys.

dict.values()
Return a new view of the dictionary’s values

dict.items()
Return a new view of the dictionary’s items ((key, value) pairs)

Example:

d={'red': 15, 'blue': 20, 'green': 3}
view_key=d.keys()
print (view_key)
#Output:dict_keys(['red', 'blue', 'green'])

view_values=d.values()
print (view_values)
#Output:dict_values([15, 20, 3])

view_items=d.items()
print (view_items)
#Output:dict_items([('red', 15), ('blue', 20), ('green', 3)])

#Inserting key-value pair to the dictionary
d["yellow"]=4

#View objects are dynamically updated
print (view_key)
#Output:dict_keys(['red', 'blue', 'green', 'yellow'])
print (view_values)
#Output:dict_values([15, 20, 3, 4])
print (view_items)
#Output:dict_items([('red', 15), ('blue', 20), ('green', 3), ('yellow', 4)])

15. What are the data types supported by keys and values in a dictionary?

A dictionary’s keys are almost arbitrary values. Values that are not hashable, that is, values containing lists, dictionaries, or other mutable types (that are compared by value rather than by object identity) may not be used as keys.

Immutable data types like strings, integers can be used as keys.

Tuples can be used as keys if they contain only strings, integers, or any immutable datatypes. If a tuple contains any mutable object either directly or indirectly, it cannot be used as a key.

Dictionary keys are unique.

Dictionary values can be of any type and can be used more than once.

Example 1:Using a list as a key in a dictionary.

d={[1]:1,'2':[2,3]}
#Output:TypeError: unhashable type: 'list'

Example 2:Dictionary keys are unique

d={'a':1,'a':2}
print (d)
#Output:{'a': 2}

Example 3:Values can be used more than once

d={'a':1,'c':1,'b':1}
print (d)
#Output:{'a': 1, 'c': 1, 'b': 1}

Note:

  • Python version used is 3.8.1.

Resources(Python Documentation)

dictionaries

mapping-types(dict)

My Other blog links related to Python dictionary

Python -dictionary

Merging dictionaries in python

Ordered dict,defaultdict

Python ChainMap

dictviewobjects

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s