regularpython@gmail.com
Dictionary
Dictionaries are used to store key-value pair type data. Each key and column is separated by a colon(:). To create an empty just use the curly braces{}. Keys are unique, we can’t make duplicates. If we take two keys are same then the last key value will be considered. Dictionaries are immutable. We can modify the data.
How to access dictionary values?
To get value from dictionary we need to use key .See the below example
student = {"name": "sairam", "Gender": "Male", "Age": 26}
print(student['name'])
print(student['Age'])
output:
sairam
26
How to update dictionary in python?
student = {"name": "sairam", "Gender": "Male", "Age": 26}
print('Before updating', student)
print('-----------------------------------------------')
student['name'] = 'Rajkumar'
print('After updating', student)
Output:
Before updating {'name': 'sairam', 'Gender': 'Male', 'Age': 26}
-----------------------------------------------
After updating {'name': 'Rajkumar', 'Gender': 'Male', 'Age': 26}
How to delete an element from dictionary in python?
del dict['name']; # remove entry with key 'name'
dict.clear(); # remove all entries in dict
del dict ; # delete entire dictionary
student = {"name": "sairam", "Gender": "Male", "Age": 26}
print('Before deleting', student)
print('-----------------------------------------------')
del student['name']
print('After deleting', student)
Output:
Before deleting {'name': 'sairam', 'Gender': 'Male', 'Age': 26}
-----------------------------------------------
After deleting {'Gender': 'Male', 'Age': 26}
In-Built functions in Dictionaries
Function |
Description |
student.clear() |
It is used to remove all elements from dictionary. |
student.copy() |
It returns shallow copy of dictionary |
student.fromkeys() |
It creates a new dictionary with keys |
student.get(key, default = None) |
If key not found returns default value |
student.has_key(key) |
Returns true if key in dictionary else false |
student.items() |
Returns a list of dict’s tuple pairs |
student.keys() |
To get all keys from dictionary. |
student.setdefault(key, default = None) |
If key is not in dictionary it sets default key and value is None. |
student.update(dict) |
To update the dictionaries |
student.values() |
It is used to returns all values from dictionary. |