Dictionary in Python3

Hi  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 return dictkeys and dict values

d= {"a": "b", "b": "c", "c": "d", "d": "e", "e": "f"}
d.keys() ---> dict_keys(['d', 'c', 'b', 'e', 'a'])
d.values() ---> dict_values(['e', 'd', 'c', 'f', 'b'])

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

list(d.keys()) ---> ['d', 'c', 'b', 'e', 'a']
list(d.values()) ---> ['e', 'd', 'c', 'f', 'b']

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

d.items() ---> dict_items([('d', 'e'), ('c', 'd'), ('b', 'c'), ('e', 'f'), ('a', 'b')])
list(d.items()) ---> [('d', 'e'), ('c', 'd'), ('b', 'c'), ('e', 'f'), ('a', 'b')]

Instead has_key() function we can check like this

'a' in d.keys() --> True
'z' in d.keys() --> False

If key doesn’t exists it will return false.

 

d.pop(‘a’) –> pop item from dict by key

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.