Saturday, 30 November 2019

Python Dictionary

PYTHON DICTIONARY


Introduction to Python – Dictionary


Dictionary is a collection of related data item pairs. 

A python dictionary is a collection of unordered items which are changeable and indexed. In Python dictionaries are written using curly brackets, and they have keys and values.


Important properties of Python - Dictionary


Un-ordered – Elements/items stored in a python dictionary are not kept in any particular order.
Changeable (mutable) – Structure and elements can be changed in place; elements can be added and removed.
Accessed by keys – Dictionary items are accessed by the keys, not by their position number (index).
Nesting Properties - Dictionaries can be nested, i.e. a dictionary can contain another dictionary in it.

Create a Python Dictionary


The dictionaries are created using curly brackets. Curly brackets contains pairs of key-value. 

>>> dist1 = {"brand":"Maruti", "model":"Desire", "year":2019}

>>> print(dist1)
{'brand': 'Maruti', 'model': 'Desire', 'year': 2019}

Accessing elements of a Python Dictionary


Following syntax can be used to access the individual elements of the python dictionary.

>>> print(dist1['brand'])
'Maruti'

>>> print(dist1['model'])
Desire

>>> print(dist1['year'])
2019

Following functions can be used to display all keys and values of the python dictionary.

>>> dist1.keys()
dict_keys(['brand', 'Model', 'Year'])

>>> dist1.values()
dict_values(['Maruti', 'Desire', 2019])


No comments:

Post a Comment