Dictionaries in Python
What is Dictionary
Creating a Dictionary
dict1={'fruits' : 'Apple', 'vegetable' : 'tomato'}
Example-1:
>>> dict1={'Fruits' : 'Apple', 'Vegetables' : 'Tomato'}
>>> dict1['Fruits']
'Apple'
>>> dict1['Vegetables']
'Tomato'
Note: Dictionaries are very flexible, that can hold any type of data types like integer, string, float, and etc.
Example-2: Collection of different data types
>>> SupperMarket={'Apple':2.50, 'Milk':1, 'Sugar':'Not Available', 'Stationary':['Pen','Pencil','Note Book']}
>>> SupperMarket['Milk']
1
>>> SupperMarket['Stationary']
['Pen', 'Pencil', 'Note Book']
>>> SupperMarket['Sugar']
'Not Available'
-- Call index on values on Dictionary
>>> SupperMarket={'Apple':2.50, 'Milk':1, 'Sugar':'Not Available', 'Stationary':['Pen','Pencil','Note Book']}
>>> SupperMarket['Stationary'][1] ------------- index position 1
'Pencil'
-- Call method on Dictionary
>>> SupperMarket={'Apple':2.50, 'Milk':1, 'Sugar':'Not Available', 'Stationary':['Pen','Pencil','Note Book']}
>>> SupperMarket['Stationary'][1].upper() ------- upper () method
'PENCIL'
Let say Sugar is available in the Super Market and we need to update the item price. Here is an example
>>> SupperMarket={'Apple':2.50, 'Milk':1, 'Sugar':'Not Available', 'Stationary':['Pen','Pencil','Note Book']}
>>> SupperMarket
{'Apple': 2.5, 'Milk': 1, 'Sugar': 'Not Available', 'Stationary': ['Pen', 'Pencil', 'Note Book']}
>>> SupperMarket['Sugar']=1.75 ---------- updating the item's value
>>> SupperMarket
{'Apple': 2.5, 'Milk': 1, 'Sugar': 1.75, 'Stationary': ['Pen', 'Pencil', 'Note Book']} ------ Sugar value is updated
>>> SupperMarket
{'Apple': 2.5, 'Milk': 1, 'Sugar': 'Not Available', 'Stationary': ['Pen', 'Pencil', 'Note Book']}
>>> SupperMarket['Sugar']=1.75 ---------- updating the item's value
>>> SupperMarket
{'Apple': 2.5, 'Milk': 1, 'Sugar': 1.75, 'Stationary': ['Pen', 'Pencil', 'Note Book']} ------ Sugar value is updated
Nesting with Dictionary
Creating a nested dictionary (dictionary inside dictionary) and calling them. Here is an example:
Example:
>>> SupperMarket_Stationary={'Stationary':{'Price':{'Pen':0.75,'Pencil':0.50,'Note Book':2}}}
>>> SupperMarket_Stationary['Stationary']['Price']['Pencil']
0.5
Dictionary Methods
There are few dictionary methods available. Here are few examples.
- keys
- values
- items
Examples:
>>> SupperMarket={'Apple':2.50, 'Milk':1, 'Sugar':'Not Available', 'Stationary':['Pen','Pencil','Note Book']}
>>> SupperMarket.keys() ----------- to list items available in SuperMarket
dict_keys(['Apple', 'Milk', 'Sugar', 'Stationary'])
>>> SupperMarket.values() ----------- to list prices available in SuperMarket
dict_values([2.5, 1, 'Not Available', ['Pen', 'Pencil', 'Note Book']])
>>> SupperMarket.items() ----------- to list all items & Prices available in SuperMarket
dict_items([('Apple', 2.5), ('Milk', 1), ('Sugar', 'Not Available'), ('Stationary', ['Pen', 'Pencil', 'Note Book'])])
Comments
Post a Comment