top of page

Python Dictionary

Dictionary is presented in key-value pair.

Create a Dictionary

d = {"Maths":75, "Science":70, "English":80}

print(d)

Dictionary cannot contain duplicate keys.

d = {"Maths":75, "Science":70, "English":80, "Maths":85}

print(d)

Access Elements

Access using the key

a = {"Maths":75, "Science":70, "English":80}

print(a["Science"])

Access using a get method.

d = {"Maths":75, "Science":70, "English":80}

print(d.get("Maths"))

Print all the keys

d = {"Maths":75, "Science":70, "English":80}

print(d.keys())

Print all the values.

d = {"Maths":75, "Science":70, "English":80}

print(d.values())

Print all the items.

d = {"Maths":75, "Science":70, "English":80}

print(d.items())

Change Elements

Elements of a dictionary can be changed or elements can be added with the help of update method

Create a Dictionary

d = {"Maths":75, "Science":70, "English":80}

d["English"] = 90

Dictionary cannot contain duplicate keys.

d = {"Maths":75, "Science":70, "English":80, "Maths":85}

d.update({"English":90})

If the key passed in the update is not present then it will create a new element and if it is present than it will update it.

Delete Elements

Elements of a dictionary can be deleted with the following methods.

Remove English from the dictionary

d = {"Maths":75, "Science":70, "English":80}

d.pop(["English"])

print(d)

Delete English using del keyword 

d = {"Maths":75, "Science":70, "English":80, "Maths":85}

del d["English"]

print(d)

Delete the complete dictionausing del keyword 

d = {"Maths":75, "Science":70, "English":80, "Maths":85}

del d

print(d)

Clear the Dictionary

d = {"Maths":75, "Science":70, "English":80, "Maths":85}

d.clear()

print(d)

Loop a Dictionary

loop on a key - Method I

d = {"Maths":75, "Science":70, "English":80}

for i in d:

    print(i)

loop on a key - Method II

d = {"Maths":75, "Science":70, "English":80}

for i in d.keys():

    print(i)

loop on a value - Method I

d = {"Maths":75, "Science":70, "English":80}

for i in d:

    print(d[i])

loop on a value - Method II

d = {"Maths":75, "Science":70, "English":80}

for i in d.values():

    print(i)

loop on a item

d = {"Maths":75, "Science":70, "English":80}

for i in d.items():

    print(i)

bottom of page