Saturday, June 20, 2015

Python - Dictionary

As the name suggests a Dictionary contains a Key and a associated value to the key. The Item (Key: Value) are separated by commas and whole thing is enclosed in a Curly Braces. While other compound data types have only value as an element, a dictionary has a key: value pair.

Keys are unique within a dictionary while values may not be. The values of a dictionary can be of any type, but the keys must be of an immutable data type such as strings, numbers, or tuples.

An empty dictionary without any items is written with just two curly braces, like this: {}.

A Dictionary can be created as,
dictionary = {'key': value, 'key': value, 'key': value}

>>> car = {'make': 'Toyota', 'door': 4, 'color': 'white'}
>>> car
{'color': 'white', 'door': 4, 'make': 'Toyota'}

>>> my_dict = {} # Empty Dictionary

Accessing – A element of a Dictionary can be accessed using the key available. It can be done as

>>> car['make']

>>> car['door']

Updating - A Dictionary can be updated or extended as

dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'};

dict['Age'] = 8; # update existing entry
dict['School'] = " School"; # Add new entry

Dictionary is mutable. We can add new items or change the value of existing items using assignment operator. If the key is already present, value gets updated, else a new key: value pair is added to the dictionary.

Deletion – Elements in the Dictionary or the entire Dict can be deleted using the del keyword as

del dict['Name']; # remove entry with key 'Name'
dict.clear();     # remove all entries in dict

No comments :

Post a Comment