Dictionary in Python

Dictionary: Python dictionary is an unordered/ unorganised collection of items. While the other compound data types have only value as an element, the dictionary has a key: value pair. Dictionary is optimised to retrieve values when the key is known.

Creating a dictionary is as simple as placing items inside curly braces {} separated by comma.

An item has a key and the corresponding value expressed as a pair, key/value.

While values can be of any data type and can repeat, keys must be of immutable type (string, number or tuple with immutable elements) and must be unique.

# empty dictionary

demo_dict = {}

# dictionary with integer keys

my_dict = {1: ‘Apple’, 2: ‘Samsung’}

# dictionary with mixed keys

my_dict = {‘name’: ‘Sumit’, 1: [2, 4, 6]}

# using dict()

demo_dict = dict({1:’Apple’, 2:’Samsung’})

# from sequence having each item as a pair

demo_dict = dict([(1,’Apple’), (2,’Sansung’)])

Add elements in a dictionary: Dictionary is mutable. We can add new items or change the value of existing items using assignment operator.

when the key is already present, value gets updated, else a new key: value pair is added to the dictionary.

demo_dict = {‘name’:’Sumit’, ‘age’: 24}

# update value

demo_dict[‘age’] = 28

print(demo_dict)

# add item

demo_dict[‘address’] = ‘Delhi’

print(demo_dict)

Leave a Reply

Your email address will not be published. Required fields are marked *