Dictionary Notes
Dictionary Notes
Creating a dictionary :
Example: Create a student dictionary with name s and keys name, class and marks.
s={
'name' : 'Sachin',
'class': 12,
'marks': 75
}
Print a dictionary:
To print a dictionary use following syntax:
print(dictionary_name)
Dictionary Length :
To determine how many items a
dictionary has, use the len() function.
Syntax: len(dictionary_name)
Looping through a dictionary: you can use for loop for this
1. To get values of a dictionary one by one, 2. To get keys of a dictionary one by one,
You can use either of the two ways given You can use either of the two ways given below.
below.
Dictionary methods:
1. keys() : It returns a list of all the keys in a dictionary.
syntax
dictionary_name.keys()
2. values() : It returns a list of all the values in a dictionary.
4. clear()
It deletes all the data from the dictionary.
5. fromkeys() : It creates and returns a new dictionary with the given keys.
All the keys will have same value if provided. If no value is provided, None is used as default.
del keyword:
Deleting a dictionary: In the given example, when we try to print dictionary s1 , it gives error. Because del
keyword has already deleted s1. So it doesn’t exist anymore. Similarly it can be used with any list or tuple.
PREV YEAR QUES: