Dictionary is a python data type that is used to store key-value pairs. It enables you to quickly retrieve, add, remove, modify, values using a key. Dictionary is very similar to what we call associative array or hash on other languages.

Note: Dictionaries are mutable.

Creating a Dictionary

Dictionaries can be created using a pair of curly braces ( {} ). Each item in the dictionary consists of a key, followed by a colon, which is followed by a value. And each item is separated using commas ( ,). Let’s take an example.

1

2

3

4

friends={

'tom':'111-222-333',

'jerry':'666-33-111'

}

here friends is a dictionary with two items. One point to note that key must be of a hashable type, but the value can be of any type. Each key in the dictionary must be unique.

1

>>>dict_emp={}# this will create an empty dictionary

Retrieving, modifying and adding elements in the dictionary

To get an item from the dictionary, use the following syntax:

1

>>>dictionary_name['key']

1

2

>>>friends['tom']

'111-222-333'

if the key exists in the dictionary, the value will be returned otherwise KeyError exception will be thrown.

To add or modify an item, use the following syntax:

1

>>>dictionary_name['newkey']='newvalue'

1

2

3

>>>friends['bob']='888-999-666'

>>>friends

{'tom':'111-222-333','bob':'888-999-666','jerry':'666-33-111'}

Deleting Items from the dictionary.

1

>>>deldictionary_name['key']

1

2

3

>>>delfriends['bob']

>>>friends

{'tom':'111-222-333','jerry':'666-33-111'}

If the key is found the item will be deleted otherwise KeyError exception will be thrown.

Other Tutorials (Sponsors)

This site generously supported by DataCamp. DataCamp offers online interactive Python Tutorials for Data Science. Join over a million other learners and get started learning Python for data science today!