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.


Author: Balaji

Hi..My name is Balaji and i am working as a Senior Software Developer in India. I am interested in Shell scripts, python, erlang , linux kernel .

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 )

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

%d bloggers like this: