A Dictionary in Python is the unordered and variable assortment of data values that holds key-value pairs. Each key-value pair in the dictionary maps the way in to its related value making it more improved. A Dictionary in python is proclaimed by encasing a comma-separated list of key-value pairs utilizing curly braces({}). Python Dictionary is grouped into two elements: Keys and Values.
Keys will be a single element
Values can be a list or list inside a list, numbers, and so forth
In this Python tutorial, you will learn:
What is a Dictionary in Python?
Syntax for Python Dictionary:
Properties of Dictionary Keys
Python Dictionary Methods
Updating Dictionary
Check if a given key already exists in a dictionary
Python Dictionary in-built Functions
Variable Types
Python List cmp() Method
Dictionary Str(dict)
Merging Dictionaries
Merge two dictionaries using update() method
Merging dictionaries using ** method (From Python 3.5 onwards)
Dictionary Membership Test
Syntax for Python Dictionary
Dict = { ' Tim': 18, xyz,.. }
Dictionary is recorded in curly brackets, inside these curly brackets, keys and values are pronounced. Each key is separated from its value by a colon (:), while commas separate every element.
Properties of Dictionary Keys
There are two significant points while utilizing dictionary keys
- More than one entry for each key isn’t permitted ( no copy key is permitted)
- The values in the dictionary can be of any kind, while the keys should be unchanging like numbers, tuples, or strings.
- Dictionary keys are case delicate Same key name but with the various cases are treated as various keys in Python dictionaries.
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']))
- In code, we have dictionary name “Dict”
- We pronounced the name and age of the individual in the dictionary, where name is “Keys” and age is the”value”
- Presently run the code
- It recovers the age of tiffany from the dictionary.
Python Dictionary Methods
Copying dictionary
You can also copy the whole dictionary to another dictionary. For example, here we have copied our unique 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)
- We have the first dictionary (Dict) with the name and age of the Boys and Girls together
- But, we need Boys list separate from Girls list, so we characterized the element of Boys and Girls in a different dictionary name “Boys” and “Girls.”
- Presently again we have made new dictionary name “student X” and “student Y,” where all the keys and values of boy dictionary are copied into student X, and the Girls will be copied in student Y.
- So presently you don’t need to investigate the entire list in the main dictionary( Dict) to check who is a boy and who is girl, you simply need to print student X if you need Boys list and Student Y if you need Girls list
- In this way, when you run the student X and student Y dictionary, it will give every one of the elements present in the dictionary of “Boys” and “Girls” independently
Updating Dictionary
You can also refresh a dictionary by adding another entry or a key-value pair to a current section or by erasing a current section. Here in the example, we will add another name, “Sarah” to our current 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)
- Our current dictionary “Dict” doesn’t have the name “Sarah.”
- We utilize the strategy Dict.update to add Sarah to our current dictionary
- Presently run the code, it adds Sarah to our current dictionary
Delete Keys from the dictionary
Python dictionary gives you the freedom to erase any element from the dictionary list. Assume you don’t need the name Charlie in the list, so you can eliminate the vital element by the accompanying 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)
Whenever you run this code, it should print the dictionary list without Charlie.
- We utilized the code del Dict
- Whenever code executed, it has erased the Charlie from the primary dictionary
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()))
- We utilize the code items() method for our Dict.
- At the point when code was executed, it returns a list of items ( keys and values) from the dictionary
Check if a given key already exists in a dictionary
For a given list, you can also check whether or not our child dictionary exists in the primary dictionary. Here we have two sub-dictionarys “Boys” and “Girls”, presently we need to check whether our dictionary Boys exist in our main “Dict” or not. For that, we utilize the for loop method with else if strategy.
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 Boys.keys():
if key in Dict.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(Boys.keys()):
if key in list(Dict.keys()):
print(True)
else:
print(False)
- The forloop in code checks each key in the fundamental dictionary for Boys keys
- In the event that it exists in the primary dictionary, it should print true or, else it should print false
- Whenever you execute the code, it will print “True” for three times, as we got three elements in our “Boys” dictionary
- So it lists that the “Boys” exist in our primary dictionary (Dict)
Sorting the Dictionary
In the dictionary, you can also sort the elements. For example, to print the name of the elements of our dictionary in order, we need to utilize the for a loop. It will sort every element of the dictionary appropriately.
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]))))
- We proclaimed the variable students for our dictionary “Dict.”
- Then, at that point, we utilize the code Students.sort, which will sort the element inside our dictionary
- Yet, to sort every element in the dictionary, we run the for a loop by announcing variable S
- Presently, when we execute the code, the for loop will call every element from the dictionary, and it will print the string and value in an order.
Python Dictionary in-built Functions
Dictionary len() Method
The len() function gives the number of pairs in the dictionary.
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 result at “4” as there are four elements in our dictionary
Variable Types
Python doesn’t need to unequivocally proclaim the save memory space; it happens naturally. The relegate values to variable “=” equal sign are utilized. The code to decide the variable kind is ” %type (Dict).”
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
Utilize the code %type to know the variable type
At the point when code was executed, it tells a variable type is a dictionary
Python List cmp() Method
The analyze method cmp() is utilized in Python to look at values and keys of two dictionarys. If method returns 0 in the event that the two dictionarys are equal, 1 if dic1 > dict2 and – 1 if dict1 < dict2.
- We have two dictionary name, “Boys” and “Girls.”
- Whichever you announce first in code “cmp(Girls, Boys)” will be considered as dictionary 1. For our situation, we pronounced “Girls” first, so it will be considered as dictionary 1 and Boys as dictionary 2
- At the point when code is executed, it prints out – 1, It demonstrates that our dictionary 1 is not as much as dictionary 2.
Dictionary Str(dict)
With Str() method, you can make a dictionary into a printable string design.
- Utilize the code % str (Dict)
- It will return the dictionary elements into a printable string design