A dictionary as a set of key: value pairs, with the requirement that the keys are unique (within one dictionary).
Dictionaries are indexed by keys, which can be any immutable type; strings and numbers or tuples with immutable objects. The values of a dictionary can be of any type.
Each key is separated from its value by a colon (:), the items are separated by commas, and the whole thing is enclosed in curly braces.
Creating a Dictionary
A pair of braces creates an empty dictionary: {}
Dictionary can also be created by the built-in function dict(). An empty dictionary can be created by just placing to curly braces{}.
Note – Dictionary keys are case sensitive, same name but different cases of Key will be treated distinctly.
Example to illustrate different ways to create a Dictionary
python"># Creating an empty Dictionary
Dict = {}
print("Empty Dictionary: ")
print(Dict)
# Creating a Dictionary with key:value pair
student_details = {'id':1234, "name":"John", 'course':'computer science','year' : 3 }
print "Student details: "
print student_details
# Creating a Dictionary with dict() method
Dict = dict({'id':1234, "name":"John", 'course' : 'computer science', 'year' : 3 })
print("\nDictionary with the use of dict(): ")
print(Dict)
# Creating a Dictionary with each item as a Pair
Dict = dict([(1, 'Geeks'), (2, 'For')])
Dict = dict([('id', 1234), ("name", "John"), ('course', 'computer science'), ('year', 3)])
print("\nDictionary with each item as a pair: ")
print(Dict)
When the above code is executed, it produces the following result −
python">Empty Dictionary:
{}
Student details:
{'course': 'computer science', 'year': 3, 'id': 1234, 'name': 'John'}
Dictionary with the use of dict():
{'course': 'computer science', 'id': 1234, 'name': 'John', 'year': 3}
Dictionary with each item as a pair:
{'course': 'computer science', 'year': 3, 'id': 1234, 'name': 'John'}
Updating a Dictionary
In Python Dictionary, Addition of elements can be done in multiple ways.
One value at a time can be added to a Dictionary by defining value along with the key e.g. Dict[Key] = ‘Value’. For Example:
python">student_details = {'id': 1234, 'course': 'computer science', 'year': 3, 'name': 'John'}
student_details["gender"] = "female" # add a new entry
print student_details
When the the above code is executed it returns the fowllowing updated student details: –
python">{'id': 1234, 'course': 'computer science', 'year': 3, 'name': 'John', “gender”: “female” }
You can modify an existing entry in a dictionary. For example, suppose we want to change the student course:
python">student_details[‘course’] = "Software Engineering" # update an existing entry
print student_details
The output of the above code when executed will be:
python">{'id': 1234, 'course': “Software Engineering”, 'year': 3, 'name': 'John', “gender”: “female” }
Updating an existing value in a Dictionary can be done by using the built-in update() method. Nested key values can also be added to an existing Dictionary.
Acc essing elements from a Dictionary
To access the items of a dictionary we refer to its key name. Key can be used inside square brackets.There is also a method called get() that will also help in acessing the element from a dictionary.
For Example to access student course and gender:
python">student_details = {'id': 1234, 'course': 'computer science', 'year': 3, 'name': 'John'}
print student[‘course’]
print student[‘gender’]
Result of the above code when executed:
"Software Engineering"
"female"
Using the get() method to access the student name
python">print student_details.get('name')
Output of the above code
"John"
Delete Dictionary Elements
You can either remove individual dictionary elements or clear the entire contents of a dictionary. You can also delete entire dictionary in a single operation.
To explicitly remove an entire dictionary, just use the del statement. For example −
python">dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
del dict['Name'] # remove entry with key 'Name'
dict.clear() # remove all entries in dict
del dict # delete entire dictionary
print "dict['Age']: ", dict['Age']
print "dict['School']: ", dict['School']
Output: Note that an exception is raised because after del dictdictionary does not exist any more
python">dict['Age']:
Traceback (most recent call last):
File "test.py", line 8, in
print "dict['Age']: ", dict['Age'];
TypeError: 'type' object is unsubscriptable
Looping Technique
When looping through dictionaries, the key and corresponding value can be retrieved at the same time using the items() method.
For example to print student_details key and val
python">students = {'course': 'computer science', 'id': 1234, 'name': 'John', 'year': 3}
for key, val in student.items():
print key, val
Output of the above code when executed:
course computer science
id 1234
name John
year 3
Built-in Dictionary Functions & Methods
Python includes the following dictionary functions −
Function with Description |
cmp(dict1, dict2) Compares elements of both dict. |
len(dict) Gives the total length of the dictionary. This would be equal to the number of items in the dictionary. |
str(dict) Produces a printable string representation of a dictionary |
type(variable) Returns the type of the passed variable. If passed variable is dictionary, then it would return a dictionary type. |
Python includes following dictionary methods −
Sr.No. |
Methods with Description |
1 |
dict.clear() Removes all elements of dictionary dict |
2 |
dict.copy() Returns a shallow copy of dictionary dict |
3 |
dict.fromkeys() Create a new dictionary with keys from seq and values set to value. |
4 |
dict.get(key, default=None) For key key, returns value or default if key not in dictionary |
5 |
dict.has_key(key) Returns true if key in dictionary dict, false otherwise |
6 |
dict.items() Returns a list of dict‘s (key, value) tuple pairs |
7 |
dict.keys() Returns list of dictionary dict’s keys |
8 |
dict.setdefault(key, default=None) Similar to get(), but will set dict[key]=default if key is not already in dict |
9 |
dict.update(dict2) Adds dictionary dict2‘s key-values pairs to dict |
10 |
dict.values() Returns list of dictionary dict‘s values |