Dictionary in Python 3

This article explains about dictionary in python3 and also difference between python 2 dictionaries and python 3 dictionaries .

Hello  all . Today we are gonna see dictionary in python3.

In python2.7

>>> d= {"a": "b", "b": "c", "c": "d", "d": "e", "e": "f"}

>>> d.keys()

['a', 'c', 'b', 'e', 'd']

>>> d.values()

['b', 'd', 'c', 'f', 'e']

>>>

Here d.keys() returns list of keys, d.values() returns list of values respectively.

In Python3 . These functions returns dict_keys and dict_values

>>> d= {"a": "b", "b": "c", "c": "d", "d": "e", "e": "f"}

>>> d.keys()

dict_keys(['e', 'a', 'c', 'b', 'd'])

>>> d.values()

dict_values(['f', 'b', 'd', 'c', 'e'])

However if we want same functionality as 2.7 we can get like this

>>> list(d.keys())

['e', 'a', 'c', 'b', 'd']

>>> list(d.values())

['f', 'b', 'd', 'c', 'e']

>>>

# There is no dict.iteritems(), d.has_key() function in python3


>>> d.items()


dict_items([('e', 'f'), ('a', 'b'), ('c', 'd'), ('b', 'c'), ('d', 'e')])

>>> list(d.items())

[('e', 'f'), ('a', 'b'), ('c', 'd'), ('b', 'c'), ('d', 'e')]

>>>

Instead has_key() function we can check like this

'a' in d.keys() # returns  True if key is present
'z' in d.keys() # returns False if key is not present

 

Other Dictionary Operations: 

  • d.pop(‘a’) . # pops item from dict by key names 'a'
  • d.popitem() # pops most recently inserted item in dict
  • d.clear() # clears entire dictionary
  • d.setdefault(‘z’, 10)  # sets default value for ‘z’ to 10
  • d.get(‘z’) –> 10 # gets value of key ‘z’, returns none if key doesn’t exist.

That's it. Thanks for reading . Happy coding !!!

Leave a comment

(Note: Comments are moderated)