Dictionary
Dictionary
PYTHON
INTRODUCTION:
CREATING A DICTIONARY:
Syntax:
Example:
>>> marks
Syntax:
dictionary-name[key]
Example:
>>> marks["Maths"]
81
>>> marks.keys( ) #To access all keys in one go
Lookup : A dictionary operation that takes a key and finds the corresponding value, is
called lookup.
TRAVERSING A DICTIONARY:
Syntax:
statement
Example:
physics : 75
Chemistry : 78
Maths : 81
CS : 78
dictionary-name[key]=value
Example:
>>> marks
>>> marks
>>> marks
{'physics': 75, 'Chemistry': 78, 'Maths': 81, 'CS': 84, 'English': 89}
Syntax:
del dictionary-name[key]
Example:
>>> marks
{'physics': 75, 'Chemistry': 78, 'Maths': 81, 'CS': 84, 'English': 89}
>>> marks
deleted element.
Syntax:
dictionary-name.pop( )
Example:
>>> marks
>>> marks.pop('Maths')
81
For pretty printing a dictionary you need to import json module and then you can use
Example:
OUTPUT:
"physics": 75,
"Chemistry": 78,
"Maths": 81,
"CS": 78
}
dumps( ) function prints key:value pair in separate lines with the number of spaces
DICTIONARY FUNCTIONS: