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. An empty dictionary without any items is written with just two curly braces, like this: {}.
Keys are unique within a dictionary while values may not be. The values of a dictionary can be of any type, but the keys must be of an immutable data type such as strings, numbers, or tuples.
Accessing Values in Dictionary
To access dictionary elements, you can use the familiar square brackets along with the key to obtain its value. Following is a simple example:
#!/usr/bin/python
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'};
print "dict['Name']: ", dict['Name']; print "dict['Age']: ", dict['Age'];
When the above code is executed, it produces the following result:
dict['Name']:Â Â Â Â Zara
dict['Age']:Â Â Â Â 7
If we attempt to access a data item with a key, which is not part of the dictionary, we get an error as follows:
#!/usr/bin/python
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'};
print "dict['Alice']: ", dict['Alice'];
When the above code is executed, it produces the following result:
dict['Zara']:
Traceback (most recent call last):
File "test.py", line 4, in <module>
print "dict['Alice']: ", dict['Alice']; KeyError: 'Alice'
Updating Dictionary
You can update a dictionary by adding a new entry or a key-value pair, modifying an existing entry, or deleting an existing entry as shown below in the simple example:
#!/usr/bin/python
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'};
dict['Age'] = 8; # update existing entry dict['School'] = "DPS School"; # Add new entry
print "dict['Age']: ", dict['Age']; print "dict['School']: ", dict['School'];
When the above code is executed, it produces the following result:
dict['Age']:Â Â Â Â 8
dict['School']:Â Â Â Â DPS School
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:
#!/usr/bin/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'];
This produces the following result. Note that an exception is raised because after del dict, dictionary does not exist anymore:
dict['Age']:
Traceback (most recent call last):
File "test.py", line 8, in <module>
print "dict['Age']: ", dict['Age']; TypeError: 'type' object is unsubscriptable
Note: del() method is discussed in subsequent section.
Properties of Dictionary Keys
Dictionary values have no restrictions. They can be any arbitrary Python object, either standard objects or user-defined objects. However, same is not true for the keys.
There are two important points to remember about dictionary keys:
(a) More than one entry per key not allowed. Which means no duplicate key is allowed. When duplicate keys encountered during assignment, the last assignment wins. For example:
#!/usr/bin/python
dict = {'Name': 'Zara', 'Age': 7, 'Name': 'Manni'};
print "dict['Name']: ", dict['Name'];
When the above code is executed, it produces the following result:
dict['Name']:Â Â Â Â Manni
(b) Keys must be immutable. Which means you can use strings, numbers or tuples as dictionary keys but something like ['key'] is not allowed. Following is a simple example:
#!/usr/bin/python
dict = {['Name']: 'Zara', 'Age': 7};
print "dict['Name']: ", dict['Name'];
When the above code is executed, it produces the following result:
Traceback (most recent call last):
File "test.py", line 3, in <module>
dict = {['Name']: 'Zara', 'Age': 7}; TypeError: list objects are unhashable
Built-in Dictionary Functions and Methods
Python includes the following dictionary functions:
Sr. No. | Function with Description |
1 | cmp(dict1, dict2) |
Compares elements of both dict. | |
2 | len(dict) |
Gives the total length of the dictionary. This would be equal to the number | |
of items in the dictionary. | |
3 | str(dict) |
Produces a printable string representation of a dictionary | |
4 | type(variable) |
Returns the type of the passed variable. If passed variable is dictionary, | |
then it would return a dictionary type. |
Let us go through these briefly:
Cmp(dict1, dict2)
Description
The method cmp() compares two dictionaries based on key and values.
Syntax
Following is the syntax for cmp() method:
cmp(dict1, dict2)
Parameters
- dict1 -- This is the first dictionary to be compared with dict2.
- dict2 -- This is the second dictionary to be compared with dict1.
Return Value
This method returns 0 if both dictionaries are equal, -1 if dict1 < dict2, and 1 if dict1 > dic2.
Example
The following example shows the usage of cmp() method.
#!/usr/bin/python
dict1 = {'Name': 'Zara', 'Age': 7}; dict2 = {'Name': 'Mahnaz', 'Age': 27}; dict3 = {'Name': 'Abid', 'Age': 27}; dict4 = {'Name': 'Zara', 'Age': 7};
print "Return Value : %d" % cmp (dict1, dict2) print "Return Value : %d" % cmp (dict2, dict3) print "Return Value : %d" % cmp (dict1, dict4)
When we run above program, it produces following result:
Return Value : -1
Return Value : 1
Return Value : 0
- len(dict)
Description
The method len() gives the total length of the dictionary. This would be equal to the number of items in the dictionary.
Syntax
Following is the syntax for len() method:
len(dict)
Parameters
- dict -- This is the dictionary, whose length needs to be calculated.
Return Value
This method returns the length.
Example
The following example shows the usage of len() method.
#!/usr/bin/python
dict = {'Name': 'Zara', 'Age': 7}; print "Length : %d" % len (dict)
When we run above program, it produces following result:
Length : 2
- str(dict)
Description
The method str() produces a printable string representation of a dictionary.
Syntax
Following is the syntax for str() method:
str(dict)
Parameters
- dict -- This is the dictionary.
Return Value
This method returns string representation.
Example
The following example shows the usage of str() method.
#!/usr/bin/python
dict = {'Name': 'Zara', 'Age': 7};
print "Equivalent String : %s" % str (dict)
When we run above program, it produces following result:
Equivalent String : {'Age': 7, 'Name': 'Zara'}
- type()
Description
The method type() returns the type of the passed variable. If passed variable is dictionary then it would return a dictionary type.
Syntax
Following is the syntax for type() method:
type(dict)
Parameters
- dict -- This is the dictionary.
Return Value
This method returns the type of the passed variable.
Example
The following example shows the usage of type() method.
#!/usr/bin/python
dict = {'Name': 'Zara', 'Age': 7};
print "Variable Type : %s" %Â Â Â Â type (dict)
When we run above program, it produces following result:
Variable Type : <type 'dict'>
Python includes following dictionary methods:
Sr. No.      Methods with Description
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 |
Let us go through them briefly:
Description
The method clear() removes all items from the dictionary.
Syntax
Following is the syntax for clear() method:
dict.clear()
Parameters
- NA
Return Value
This method does not return any value.
Example
The following example shows the usage of clear() method.
#!/usr/bin/python
dict = {'Name': 'Zara', 'Age': 7};
print "Start Len : %d" % len(dict) dict.clear()
print "End Len : %d" %Â Â Â Â len(dict)
When we run above program, it produces following result:
Start Len : 2
End Len : 0
- Dict.copy()
Description
The method copy() returns a shallow copy of the dictionary.
Syntax
Following is the syntax for copy() method:
dict.copy()
Parameters
- NA
Return Value
This method returns a shallow copy of the dictionary.
Example
The following example shows the usage of copy() method.
#!/usr/bin/python
dict1 = {'Name': 'Zara', 'Age': 7};
dict2 = dict1.copy()
print "New Dictinary : %s" %Â Â Â Â str(dict2)
When we run above program, it produces following result:
New Dictinary : {'Age': 7, 'Name': 'Zara'}
- Dict.fromkeys()
Description
The method fromkeys() creates a new dictionary with keys from seq and values set to value.
Syntax
Following is the syntax for fromkeys() method:
dict.fromkeys(seq[, value]))
Parameters
- seq -- This is the list of values which would be used for dictionary keys
- value -- This is optional, if provided then value would be set to this value
Return Value
This method returns the list.
Example
The following example shows the usage of fromkeys() method.
#!/usr/bin/python
seq = ('name', 'age', 'sex')
dict = dict.fromkeys(seq)
print "New Dictionary : %s" %Â Â Â Â str(dict)
dict = dict.fromkeys(seq, 10)
print "New Dictionary : %s" %Â Â Â Â str(dict)
When we run above program, it produces following result:
New Dictionary : {'age': None, 'name': None, 'sex': None}
New Dictionary : {'age': 10, 'name': 10, 'sex': 10}
- Dict.get(key,default=none)
Description
The method get() returns a value for the given key. If key is not available then returns default value None.
Syntax
Following is the syntax for get() method:
dict.get(key, default=None)
Parameters
- key -- This is the Key to be searched in the dictionary.
- default -- This is the Value to be returned in case key does not exist.
Return Value
This method return a value for the given key. If key is not available, then returns default value None.
Example
The following example shows the usage of get() method.
#!/usr/bin/python
dict = {'Name': 'Zabra', 'Age': 7}
print "Value : %s" %Â Â Â Â dict.get('Age')
print "Value : %s" %Â Â Â Â dict.get('Education', "Never")
When we run above program, it produces the following result:
Value : 7
Value : Never
- Dict.has_key(key)
Description
The method has_key() returns true if a given key is available in the dictionary, otherwise it returns a false.
Syntax
Following is the syntax for has_key() method:
dict.has_key(key)
Parameters
- key -- This is the Key to be searched in the dictionary.
Return Value
This method return true if a given key is available in the dictionary, otherwise it returns a false.
Example
The following example shows the usage of has_key() method.
#!/usr/bin/python
dict = {'Name': 'Zara', 'Age': 7}
print "Value : %s" % dict.has_key('Age') print "Value : %s" % dict.has_key('Sex')
When we run above program, it produces following result:
Value : True
Value : False
- Dict.items()
Description
The method items() returns a list of dict's (key, value) tuple pairs
Syntax
Following is the syntax for items() method:
dict.items()
Parameters
- NA
Return Value
This method returns a list of tuple pairs.
Example
The following example shows the usage of items() method.
#!/usr/bin/python
dict = {'Name': 'Zara', 'Age': 7}
print "Value : %s" %Â Â Â Â dict.items()
When we run above program, it produces following result:
Value : [('Age', 7), ('Name', 'Zara')]
- Dict.keys()
Description
The method keys() returns a list of all the available keys in the dictionary.
Syntax
Following is the syntax for keys() method:
dict.keys()
Parameters
NA
Return Value
This method returns a list of all the available keys in the dictionary.
Example
The following example shows the usage of keys() method.
#!/usr/bin/python
dict = {'Name': 'Zara', 'Age': 7}
print "Value : %s" %Â Â Â Â dict.keys()
When we run above program, it produces following result:
Value : ['Age', 'Name']
dict.setdefault(key, default=None)
Description
The method setdefault() is similar to get(), but will set dict[key]=default if key is not already in dict.
Syntax
Following is the syntax for setdefault() method:
dict.setdefault(key, default=None)
Parameters
- key -- This is the key to be searched.
- default -- This is the Value to be returned in case key is not found.
Return Value
This method returns the key value available in the dictionary and if given key is not available then it will return provided default value.
Example
The following example shows the usage of setdefault() method.
#!/usr/bin/python
dict = {'Name': 'Zara', 'Age': 7}
print "Value : %s" % dict.setdefault('Age', None) print "Value : %s" % dict.setdefault('Sex', None)
When we run above program, it produces following result:
Value : 7
Value : None
dict.update(dict2)
Description
The method update() adds dictionary dict2's key-values pairs in to dict. This function does not return anything.
Syntax
Following is the syntax for update() method:
dict.update(dict2)
Parameters
- dict2 -- This is the dictionary to be added into dict.
Return Value
This method does not return any value.
Example
The following example shows the usage of update() method.
#!/usr/bin/python
dict = {'Name': 'Zara', 'Age': 7} dict2 = {'Sex': 'female' }
dict.update(dict2)
print "Value : %s" %Â Â Â Â dict
When we run above program, it produces following result:
Value : {'Age': 7, 'Name': 'Zara', 'Sex': 'female'}
- dict.values()
Description
The method values() returns a list of all the values available in a given dictionary.
Syntax
Following is the syntax for values() method:
dict.values()
Parameters
NA
Return ValueÂ
This method returns a list of all the values available in a given dictionary.
Example
The following example shows the usage of values() method.
#!/usr/bin/python
dict = {'Name': 'Zara', 'Age': 7}
print "Value : %s" %Â Â Â Â dict.values()
When we run above program, it produces following result:
Value : [7, 'Zara']
#############################################
Python Dictionaries
Dictionary
A dictionary is a collection which is unordered, changeable and indexed. In Python dictionaries are written with curly brackets, and they have keys and values.
Example
Create and print a dictionary:
thisdict = {
"brand":Â "Ford",
"model":Â "Mustang",
"year":Â 1964
}
print(thisdict)
Accessing Items
You can access the items of a dictionary by referring to its key name, inside square brackets:
Example
Get the value of the "model" key:
x = thisdict["model"]
There is also a method called get()
 that will give you the same result:
Example
Get the value of the "model" key:
x = thisdict.get("model")
Change Values
You can change the value of a specific item by referring to its key name:
Example
Change the "year" to 2018:
thisdict = {
"brand":Â "Ford",
"model":Â "Mustang",
"year":Â 1964
}
thisdict["year"] =Â 2018
Loop Through a Dictionary
You can loop through a dictionary by using a for
 loop.
When looping through a dictionary, the return value are the keys of the dictionary, but there are methods to return the values as well.
Example
Print all key names in the dictionary, one by one:
for x in thisdict:
print(x)
Example
Print all values in the dictionary, one by one:
for x in thisdict:
print(thisdict[x])
Example
You can also use the values()
 function to return values of a dictionary:
for x in thisdict.values():
print(x)
Example
Loop through both keys and values, by using the items()
 function:
for x, y in thisdict.items():
print(x, y)
Check if Key Exists
To determine if a specified key is present in a dictionary use the in
 keyword:
Example
Check if "model" is present in the dictionary:
thisdict = {
"brand":Â "Ford",
"model":Â "Mustang",
"year":Â 1964
}
if "model" in thisdict:
print("Yes, 'model' is one of the keys in the thisdict dictionary")
Dictionary Length
To determine how many items (key-value pairs) a dictionary has, use the len()
 method.
Example
Print the number of items in the dictionary:
print(len(thisdict))
Adding Items
Adding an item to the dictionary is done by using a new index key and assigning a value to it:
Example
thisdict = {
"brand":Â "Ford",
"model":Â "Mustang",
"year":Â 1964
}
thisdict["color"] =Â "red"
print(thisdict)
Removing Items
There are several methods to remove items from a dictionary:
Example
The pop()
 method removes the item with the specified key name:
thisdict = {
"brand":Â "Ford",
"model":Â "Mustang",
"year":Â 1964
}
thisdict.pop("model")
print(thisdict)
Example
The popitem()
 method removes the last inserted item (in versions before 3.7, a random item is removed instead):
thisdict = {
"brand":Â "Ford",
"model":Â "Mustang",
"year":Â 1964
}
thisdict.popitem()
print(thisdict)
Example
The del
 keyword removes the item with the specified key name:
thisdict = {
"brand":Â "Ford",
"model":Â "Mustang",
"year":Â 1964
}
del thisdict["model"]
print(thisdict)
Example
The del
 keyword can also delete the dictionary completely:
thisdict = {
"brand":Â "Ford",
"model":Â "Mustang",
"year":Â 1964
}
del thisdict
print(thisdict)Â #this will cause an error because "thisdict" no longer exists.
Example
The clear()
 keyword empties the dictionary:
thisdict = {
"brand":Â "Ford",
"model":Â "Mustang",
"year":Â 1964
}
thisdict.clear()
print(thisdict)
Copy a Dictionary
You cannot copy a dictionary simply by typing dict2 = dict1
, because:Â dict2
 will only be a reference to dict1
, and changes made in dict1
 will automatically also be made in dict2
.
There are ways to make a copy, one way is to use the built-in Dictionary method copy()
.
Example
Make a copy of a dictionary with the copy()
 method:
thisdict = {
"brand":Â "Ford",
"model":Â "Mustang",
"year":Â 1964
}
mydict = thisdict.copy()
print(mydict)
Another way to make a copy is to use the built-in method dict()
.
Example
Make a copy of a dictionary with the dict()
 method:
thisdict = {
"brand":Â "Ford",
"model":Â "Mustang",
"year":Â 1964
}
mydict = dict(thisdict)
print(mydict)
The dict() Constructor
It is also possible to use the dict() constructor to make a new dictionary:
Example
thisdict = dict(brand="Ford", model="Mustang", year=1964)
# note that keywords are not string literals
# note the use of equals rather than colon for the assignment
print(thisdict)
Dictionary Methods
Python has a set of built-in methods that you can use on dictionaries.
Method | Description |
---|---|
clear() | Removes all the elements from the dictionary |
copy() | Returns a copy of the dictionary |
fromkeys() | Returns a dictionary with the specified keys and values |
get() | Returns the value of the specified key |
items() | Returns a list containing the a tuple for each key value pair |
keys() | Returns a list containing the dictionary's keys |
pop() | Removes the element with the specified key |
popitem() | Removes the last inserted key-value pair |
setdefault() | Returns the value of the specified key. If the key does not exist: insert the key, with the specified value |
update() | Updates the dictionary with the specified key-value pairs |
values() | Returns a list of all the values in the dictionary |
#########################
#############################################
p1={"name":"a","age":23,"city":"hyd","frnds":["c","b","e"]}
p2={"name":"b","age":22,"city":"Bng","frnds":["c","f","e","h"]}
print(p1)
print("key=","name", "value=", p1["name"])
#Update
p1["city"]="bng"
print("total items",len(p1))
if("city" in p1):
print("key is there")
# Delete
del p1["city"]
#iterator Access
for key in p1:
print("key=",key,"value=",p1[key])
#########
p1={"name":"a","age":23,"city":"hyd","friends":["b","c","d","e"]}
p2={"name":"b","age":23,"city":"hyd","friends":["a","c","d","g"]}
p1_frnds=p1["friends"]
p2_frnds=p2["friends"]
print("p1 frnds:",p1_frnds)
print("p2 frnds:",p2_frnds)
print("mutual friends")
for f1 in p1_frnds:
for f2 in p2_frnds:
if(f1==f2):
print(f1)
#print(d.items())
#print(len(d))
#print('name' in d.keys())
#for key in d:
# print(key,":",d[key])
@@@
p1={"name":"a","age":23,"city":"hyd","frnds":["c","b","e"]}
p2={"name":"b","age":22,"city":"Bng","frnds":["c","f","e","h"]}
s1=set(p1["frnds"])
print(s1)
s2=set(p2["frnds"])
print(s2)
print("common friends:",s1&s2)
##########################################
d={"name":"abc","age":20}
print(d["name"])
d["name"]="xyz"
print(d["name"])
for k in d:
print("key:",k)
print("value:",d[k])
print("age1" in d)
d["clg"]="xyz"
print(d)
d.pop("clg")
print(d)
d2=d.copy()
print(d2)
d3=dict(d)
print(d3)
print(d.keys())
l=d.keys()
print(list(l))
print(d.values())