Python Dictionaries

You can use List, Tuple and Set to represent a group of individual objects as a single entity. If you want to represent a group of objects as key-value pairs then you should go for Dictionary. Here we will go through into various scenarios of python Dictionaries.

  • Duplicate keys can not be used but values can be duplicated.
  • Heterogeneous objects can be used for both key and values.
  • insertion order is not preserved.
  • Dictionaries are mutable and dynamic.
  • indexing and slicing concepts are not applicable.
dict = {key:value, key:value}

Creating Dictionary

You can create empty dictionary as follows,

d={} or d=dict()

You can add entries as follows

d[100]="Python"
d[200]="ravi"
d[300]="inder"

print(d) 

{100: 'Python', 200: 'ravi', 300: 'inder'}

If you know data in advance then you can create dictionary as follows

d={100:'durga' ,200:'ravi', 300:'shiva'}

Accessing data from a dictionary

You can access data by using keys.

d={100:'python' ,200:'ravi', 300:'inder'}
print(d[100]) 
print(d[300]) 

Output

python
inder

If the specified key is not available then you will get KeyError

print(d[400])

KeyError: 400

You can prevent this by checking whether key is already available or not by using has_key() function or by using in operator.

d.has_key(400)
1

it returns 1 if key is available otherwise returns 0

But has_key() function is only available in Python 2.x but not in Python 3.x. Hence compulsory we have to use in operator.

if 400 in d:
    print(d[400])

Updating Dictionaries

If key is not available then a new entry will be added with the specified key-value pair to the dictionary If the key is already available then old value will be replaced with the new value.

d[key]=value
d={100:"Python",200:"Ravi",300:"Inder"}
print(d)
d[400]="Ankur"
print(d)
d[100]="Vinit"
print(d)

Output

{100:"Python",200:"Ravi",300:"Inder"}
{100:"Python",200:"Ravi",300:"Inder",400:"Ankur",}
{100:"Python",200:"Ravi",300:"Inder",400:"Ankur",500:"Vinit"}

Deleting elements from dictionary

del d[key]

It deletes entry associated with the specified key. If the key is not available then you will get KeyError

d={100:"Python",200:"Ravi",300:"Inder"}
print(d)
del d[100]
print(d)
del d[400]

Output

{200: 'Ravi', 300: 'Inder'}

d.clear()

To remove all entries from the dictionary

d={100:"Python",200:"Ravi",300:"Inder"}
print(d)
d.clear()
print(d)

Output

{100:"Python",200:"Ravi",300:"Inder"}
{}

del d

To delete total dictionary.Now we cannot access d

d={100:"Python",200:"Ravi",300:"Inder"}
print(d)
del d
print(d)

Output

{100: 'durga', 200: 'ravi', 300: 'shiva'}
NameError: name 'd' is not defined

Important functions of dictionary

1. dict()

To create a dictionary, dict() function can be used.

d=dict() ===> It creates empty dictionary
d=dict({100:”Python”,200:”Ravi”})  ==>It creates dictionary with specified elements
d=dict([(100,”Python”),(200,”Ravi”),(300,”Inder”)])   ==>It creates dictionary with the given list of tuple elements

2. len()

Returns the number of items in the dictionary.

3. clear()

To remove all elements from the dictionary.

4. get()

To get the value associated with the key.

If the key is available then it returns the corresponding value otherwise it will return None. It wont raise any error.
If the key is available then it returns the corresponding value otherwise it will return default value.

d={100:"Python",200:"Ravi",300:"Inder"}

print(d[100])    ==> Python
print(d[400]) ==> KeyError:400
print(d.get(100)) ==>  Python
print(d.get(400)) ==> None
print(d.get(100,"Guest")) ==> durga
print(d.get(400,"Guest")) ==> Guest

5. pop()

This d.pop(key) functions removes the entry associated with the specified key and returns the corresponding value. If the specified key is not available then you will get KeyError.

d={100:"Python",200:"Ravi",300:"Inder"}
print(d.pop(100))
print(d)
print(d.pop(400))

Output

Python
{200: 'Ravi', 300: 'Inder'}
KeyError: 400

6. keys()

It returns all keys associated with dictionary.

d={100:"Python",200:"Ravi",300:"Inder"}
print(d.keys())
for k in d.keys():
    print(k)

Output

dict_keys([100, 200, 300])
100
200
300

7. values()

It returns all values associated with the dictionary

d={100:"Python",200:"Ravi",300:"Inder"}
print(d.values())
for v in d.values():
    print(v)

Output

dict_values(['Python', 'Ravi', 'Inder'])
Python
Ravi
Inder

8. items()

It returns list of tuples representing key-value pairs.

[(k,v),(k,v),(k,v)]

d={100:"Python",200:"Ravi",300:"Inder"}
for k,v in d.items():
    print(k,"--",v)

Output

100 -- Python
200 -- Ravi
300 -- Inder

9. copy()

To create exactly duplicate dictionary(cloned copy)

d={100:"Python",200:"Ravi",300:"Inder"}
d1=d.copy()
print(d1)

Output

{100: 'Python', 200: 'Ravi', 300: 'Inder'}

10. setdefault()

If the key is already available then it returns the corresponding value. If the key is not available then this will add specified key-value as new item to the dictionary.

d={100:"Python",200:"Ravi",300:"Inder"}
print(d.setdefault(400,"pawan"))
print(d)
print(d.setdefault(100,"sachin"))
print(d)

Output

pawan
{100: 'Python', 200: 'Ravi', 300: 'Inder', 400: 'pawan'}
Python
{100: 'Python', 200: 'Ravi', 300: 'Inder', 400: 'pawan'}

Read Also : Python Sets

Share on:

Ravindra Kumar

Hi, This is Ravindra. I am founder of TheCodeCloud. I am AWS Certified Solutions Architect Associate & Certified in Oracle Cloud as well. I am DevOps and Data Science Enthusiast.

Recommended Reading..

1 thought on “Python Dictionaries”

Leave a Comment