Python Dictionary(Dict): Update, Cmp, Len, Sort, Copy, Items, str Example

What is a Dictionary in Python?

A Dictionary in Python is the unordered and changeable collection of data values that holds key-value pairs. Each key-value pair in the dictionary maps the key to its associated value making it more optimized. A Dictionary in python is declared by enclosing a comma-separated list of key-value pairs using curly braces({}). Python Dictionary is classified into two elements: Keys and Values.

In this Python tutorial, you will learn:

Syntax for Python Dictionary

Dict = { ' Tim': 18,  xyz,.. }

Dictionary is listed in curly brackets, inside these curly brackets, keys and values are declared. Each key is separated from its value by a colon (:), while commas separate each element.

Properties of Dictionary Keys

There are two important points while using dictionary keys

Python 2 Example

Dict = {'Tim': 18,'Charlie':12,'Tiffany':22,'Robert':25}   
print (Dict['Tiffany'])

Python 3 Example

Dict = {'Tim': 18,'Charlie':12,'Tiffany':22,'Robert':25}   
print((Dict['Tiffany']))

Python Dictionary Methods

Copying dictionary

You can also copy the entire dictionary to a new dictionary. For example, here we have copied our original dictionary to the new dictionary name "Boys" and "Girls".

Python 2 Example

Dict = {'Tim': 18,'Charlie':12,'Tiffany':22,'Robert':25}	
Boys = {'Tim': 18,'Charlie':12,'Robert':25}
Girls = {'Tiffany':22}	
studentX=Boys.copy()
studentY=Girls.copy()
print studentX
print studentY

Python 3 Example

Dict = {'Tim': 18,'Charlie':12,'Tiffany':22,'Robert':25}	
Boys = {'Tim': 18,'Charlie':12,'Robert':25}
Girls = {'Tiffany':22}	
studentX=Boys.copy()
studentY=Girls.copy()
print(studentX)
print(studentY)

Updating Dictionary

You can also update a dictionary by adding a new entry or a key-value pair to an existing entry or by deleting an existing entry. Here in the example, we will add another name, "Sarah" to our existing dictionary.

Python 2 Example

Dict = {'Tim': 18,'Charlie':12,'Tiffany':22,'Robert':25}	
Dict.update({"Sarah":9})
print Dict

Python 3 Example

Dict = {'Tim': 18,'Charlie':12,'Tiffany':22,'Robert':25}	
Dict.update({"Sarah":9})
print(Dict)

Delete Keys from the dictionary

Python dictionary gives you the liberty to delete any element from the dictionary list. Suppose you don't want the name Charlie in the list, so you can remove the key element by the following code.

Python 2 Example

Dict = {'Tim': 18,'Charlie':12,'Tiffany':22,'Robert':25}	
del Dict ['Charlie']
print Dict

Python 3 Example

Dict = {'Tim': 18,'Charlie':12,'Tiffany':22,'Robert':25}	
del Dict ['Charlie']
print(Dict)

When you run this code, it should print the dictionary list without Charlie.

Dictionary items() Method

The items() method returns a list of tuple pairs (Keys, Value) in the dictionary.

Python 2 Example

Dict = {'Tim': 18,'Charlie':12,'Tiffany':22,'Robert':25}	
print "Students Name: %s" % Dict.items()

Python 3 Example

Dict = {'Tim': 18,'Charlie':12,'Tiffany':22,'Robert':25}	
print("Students Name: %s" % list(Dict.items()))

Check if a given key already exists in a dictionary

For a given list, you can also check whether our child dictionary exists in the main dictionary or not. Here we have two sub-dictionaries "Boys" and "Girls", now we want to check whether our dictionary Boys exist in our main "Dict" or not. For that, we use the for loop method with else if method.

Python 2 Example

Dict = {'Tim': 18,'Charlie':12,'Tiffany':22,'Robert':25}
Boys = {'Tim': 18,'Charlie':12,'Robert':25}
Girls = {'Tiffany':22}
for key in Dict.keys():
    if key in Boys.keys():
        print True
    else:       
        print False

Python 3 Example

Dict = {'Tim': 18,'Charlie':12,'Tiffany':22,'Robert':25}
Boys = {'Tim': 18,'Charlie':12,'Robert':25}
Girls = {'Tiffany':22}
for key in list(Dict.keys()):
    if key in list(Boys.keys()):
        print(True)
    else:       
        print(False)

Sorting the Dictionary

In the dictionary, you can also sort the elements. For example, if we want to print the name of the elements of our dictionary alphabetically, we have to use the for a loop. It will sort each element of the dictionary accordingly.

Python 2 Example

Dict = {'Tim': 18,'Charlie':12,'Tiffany':22,'Robert':25}
Boys = {'Tim': 18,'Charlie':12,'Robert':25}
Girls = {'Tiffany':22}
Students = Dict.keys()
Students.sort()
for S in Students:
      print":".join((S,str(Dict[S])))

Python 3 Example

Dict = {'Tim': 18,'Charlie':12,'Tiffany':22,'Robert':25}
Boys = {'Tim': 18,'Charlie':12,'Robert':25}
Girls = {'Tiffany':22}
Students = list(Dict.keys())
Students.sort()
for S in Students:
      print(":".join((S,str(Dict[S]))))

Python Dictionary in-built Functions

Dictionary len() Method

The len() function gives the number of pairs in the dictionary.

For example,

Python 2 Example

Dict = {'Tim': 18,'Charlie':12,'Tiffany':22,'Robert':25}	
print "Length : %d" % len (Dict)

Python 3 Example

Dict = {'Tim': 18,'Charlie':12,'Tiffany':22,'Robert':25}	
print("Length : %d" % len (Dict))

When len (Dict) function is executed it gives the output at "4" as there are four elements in our dictionary

Variable Types

Python does not require to explicitly declare the reserve memory space; it happens automatically. The assign values to variable "=" equal sign are used. The code to determine the variable type is " %type (Dict)."

Python 2 Example

Dict = {'Tim': 18,'Charlie':12,'Tiffany':22,'Robert':25}	
print "variable Type: %s" %type (Dict)

Python 3 Example

Dict = {'Tim': 18,'Charlie':12,'Tiffany':22,'Robert':25}	
print("variable Type: %s" %type (Dict))

Python List cmp() Method

The compare method cmp() is used in Python to compare values and keys of two dictionaries. If method returns 0 if both dictionaries are equal, 1 if dic1 > dict2 and -1 if dict1 < dict2.

Python 2 Example

Boys = {'Tim': 18,'Charlie':12,'Robert':25}
Girls = {'Tiffany':22}	
print cmp(Girls, Boys)

Python 3 Example

cmp is not supported in Python 3

Dictionary Str(dict)

With Str() method, you can make a dictionary into a printable string format.

Python 2 Example

Dict = {'Tim': 18,'Charlie':12,'Tiffany':22,'Robert':25}	
print "printable string:%s" % str (Dict)

Python 3 Example

Dict = {'Tim': 18,'Charlie':12,'Tiffany':22,'Robert':25}	
print("printable string:%s" % str (Dict))

Here is the list of all Dictionary Methods

Method Description Syntax
copy() Copy the entire dictionary to new dictionary dict.copy()
update() Update a dictionary by adding a new entry or a key-value pair to anexisting entry or by deleting an existing entry. Dict.update([other])
items() Returns a list of tuple pairs (Keys, Value) in the dictionary. dictionary.items()
sort() You can sort the elements dictionary.sort()
len() Gives the number of pairs in the dictionary. len(dict)
cmp() Compare the values and keys of two dictionaries cmp(dict1, dict2)
Str() Make a dictionary into a printable string format Str(dict)

Merging Dictionaries

Here will understand how to merge two given dictionaries into a single dictionary.

I have two dictionaries as shown below :

Dictionary1 : my_dict1

my_dict1 = {"username": "XYZ", "email": "This email address is being protected from spambots. You need JavaScript enabled to view it.", "location":"Mumbai"}

Dictionary 2 : my_dict2

my_dict2 = {"firstName" : "Nick", "lastName": "Price"}

Let us merge both these dictionaries my_dict1 and my_dict2 and create a single dictionary with namemy_dict.

Merge two dictionaries using update() method

The update() method will help us to merge one dictionary with another. In the example, we will update the my_dict1 with my_dict2. After using update() method the my_dict1 will have the contents of my_dict2 as shown below:

my_dict1 = {"username": "XYZ", "email": "This email address is being protected from spambots. You need JavaScript enabled to view it.", "location":"Mumbai"}

my_dict2 = {"firstName" : "Nick", "lastName": "Price"}

my_dict1.update(my_dict2)

print(my_dict1)

Output:

{'username': 'XYZ', 'email': This email address is being protected from spambots. You need JavaScript enabled to view it.', 'location': 'Mumbai', 'firstName': 'Nick', 'lastName': 'Price'}

Merging dictionaries using ** method (From Python 3.5 onwards)

The ** is called Kwargs in Python, and it will work with Python version 3.5+. Using **, we can merge two dictionaries, and it will return the merged dictionary. Making use of ** in front of the variable will replace the variable with all its content.

Here is a working example of using ** to merge two directories.

my_dict1 = {"username": "XYZ", "email": "This email address is being protected from spambots. You need JavaScript enabled to view it.", "location":"Mumbai"}

my_dict2 = {"firstName" : "Nick", "lastName": "Price"}

my_dict =  {**my_dict1, **my_dict2} 

print(my_dict)

Output:

{'username': 'XYZ', 'email': This email address is being protected from spambots. You need JavaScript enabled to view it.', 'location': 'Mumbai', 'firstName': 'Nick', 'lastName': 'Price'}

Dictionary Membership Test

You can test if a key in the present inside a dictionary or not. This test can be performed only on the key of a dictionary and not the value. The membership test is done using the in keyword. When you check the key in the dictionary using the in keyword, the expression returns true if the key is present and false if not.

Here is an example that shows member ship test on a dictionary.

my_dict = {"username": "XYZ", "email": "This email address is being protected from spambots. You need JavaScript enabled to view it.", "location":"Mumbai"}
print("email" in my_dict)
print("location" in my_dict)
print("test" in my_dict)

Output:

True
True
False

Summary:

 

YOU MIGHT LIKE: