Definition
A Python dictionary is a collection of "key"
and"value"
pairs.
Dictionaries are "unordered"
, "indexed"
, "mutable"
i.e. can be changed after their creation, and are enclosed with "curly brackets {}"
.
These are "mapping"
type data-type in Python.
Keys and values are separated by "colon(:)"
and key-value pairs are separated using "comma(,)"
.
Keys
Keys can be a "single element"
only and should be immutable Python objects i.e. "numbers"
, "strings"
, and "tuples"
.
Values
A value in a dictionary can be any Python object like "list"
, "tuple"
, "number"
, "string"
, and even the "dictionary"
.
Creating a Dictionary
Example
mydict = {"key1" : "Value1","key2" : "Value2","key3" : "Value3"}print(mydict)print(type(mydict))
Output
{'key1': 'Value1', 'key2': 'Value2', 'key3': 'Value3'}<class 'dict'>
dict() method
We can also use "dict()"
method to create a dictionary.
Example
myDict = dict(key1="value1", key2="value2",key3="value3")print(type(myDict))print(myDict)
Output
<class 'dict'>{'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}
Accessing values
We can access dictionary values using a "key name"
or using "get()"
method.
Example
mydict = {"key1" : "Value1","key2" : "Value2","key3" : "Value3"}print(mydict)print(mydict["key1"])print(mydict.get("key2"))
Output
{'key1': 'Value1', 'key2': 'Value2', 'key3': 'Value3'}Value1Value2
Updating Dictionary
We can add more key-value pairs in a dictionary, change the value of a key, and can also take value from the user at run time.
Use "dictname[keyname] = value"
to add or change a key-value pair.
If the keyname does not exist then a new key-value pair will be created and added to the dictionary else the value of the key will be changed.
We can also take a key’s value from the user at run time of the Python code using "input()"
function.
Example
mydict = {"key1" : "Value1","key2" : "Value2","key3" : "Value3"}print(mydict)mydict["newkey1"] = "newvalue1"mydict["key1"] = "updatedvalue1"print(mydict)mydict["userinput"] = input("Enter value: ")print(mydict)
Output
{'key1': 'Value1', 'key2': 'Value2', 'key3': 'Value3'}{'key1': 'updatedvalue1', 'key2': 'Value2', 'key3': 'Value3', 'newkey1': 'newvalue1'}Enter value: myinputvalue{'key1': 'updatedvalue1', 'key2': 'Value2', 'key3': 'Value3', 'newkey1': 'newvalue1', 'userinput': 'myinputvalue'}
We can also use "update()"
method to add many key-value pairs at one time.
Example
mydict = {"key1" : "Value1","key2" : "Value2","key3" : "Value3"}print(mydict)mydict.update({"key4":"value4", "key5":"value5", "key6":"value6"})print(mydict)
Output
{'key1': 'Value1', 'key2': 'Value2', 'key3': 'Value3'}{'key1': 'Value1', 'key2': 'Value2', 'key3': 'Value3', 'key4': 'value4', 'key5': 'value5', 'key6': 'value6'}
Dictionary Length
We can determine the number of key-value pairs using "len()"
method.
Example
mydict = {"key1" : "Value1","key2" : "Value2","key3" : "Value3"}print(len(mydict))
Output
3
Checking a Key in Dictionary
We can check whether a key-value pair exists in a dictionary using in keyword "in"
Python.
Example
mydict = {"key1" : "Value1","key2" : "Value2","key3" : "Value3"}print("key1" in mydict)print("key2" in mydict)print("key5" in mydict)
Output
TrueTrueFalse
del keyword
Use "del"
keyword to delete a key-value pair in a dictionary.
Syntax– del dictname["keyname"]
Note– this keyword can also be used to delete the entire dictionary.
Syntax– del dictname
Example
mydict = {"key1" : "Value1","key2" : "Value2","key3" : "Value3"}print(mydict)del mydict["key1"]print(mydict)del mydictprint(mydict)
Output
{'key1': 'Value1', 'key2': 'Value2', 'key3': 'Value3'}{'key2': 'Value2', 'key3': 'Value3'}Traceback (most recent call last):File "f:/vscode/python/dicttutorial.py", line 10, in <module>print(mydict)NameError: name 'mydict' is not defined
pop() method
We can also use "pop()"
method to remove any key-value pair using the specified key name.
Example
mydict = {"key1" : "Value1","key2" : "Value2","key3" : "Value3"}print(mydict)mydict.pop("key1")print(mydict)mydict.pop("key2")print(mydict)
Output
{'key1': 'Value1', 'key2': 'Value2', 'key3': 'Value3'}{'key2': 'Value2', 'key3': 'Value3'}{'key3': 'Value3'}
popitem() method
This method simply removes the last key-value pair present in the dictionary.
Note– In versions before 3.7, it was used to remove a random key-value pair.
Example
mydict = {"key1" : "Value1","key2" : "Value2","key3" : "Value3"}print(mydict)mydict.popitem()print(mydict)mydict.popitem()print(mydict)
Output
{'key1': 'Value1', 'key2': 'Value2', 'key3': 'Value3'}{'key1': 'Value1', 'key2': 'Value2'}{'key1': 'Value1'}
clear() method
If we want to make our dictionary completely empty then we can use this method.
This method will remove all the key-value pairs from the dictionary but the name of the dictionary will be available as it was before.
Example
mydict = {"key1" : "Value1","key2" : "Value2","key3" : "Value3"}print(mydict)mydict.clear()print(mydict)
Output
{'key1': 'Value1', 'key2': 'Value2', 'key3': 'Value3'}{}
Copy a Dictionary
We can directly assign a dictionary to any variable using the assignment operator"(=)"
.
But this will not be called as copying a dictionary because here we are only referring to the old dictionary using the assignment operator like we simply assign some value to any variable"a = 5"
.
So, if we make any changes in the previous dictionary, then we will see those changes in our new copied dictionary.
Example
mydict = {"key1" : "Value1","key2" : "Value2","key3" : "Value3"}newdict = mydictprint(mydict)print(newdict)mydict["key1"] = "newvalue"print(mydict)print(newdict)
Output
{'key1': 'Value1', 'key2': 'Value2', 'key3': 'Value3'}{'key1': 'Value1', 'key2': 'Value2', 'key3': 'Value3'}{'key1': 'newvalue', 'key2': 'Value2', 'key3': 'Value3'}{'key1': 'newvalue', 'key2': 'Value2', 'key3': 'Value3'}
Use "copy()"
method if you want to create a new copied dictionary.
Example
mydict = {"key1" : "Value1","key2" : "Value2","key3" : "Value3"}newdict = mydict.copy()print(newdict)mydict["key1"] = "newvalue"print(mydict)print(newdict) # newdict will not be effected
Output
{'key1': 'Value1', 'key2': 'Value2', 'key3': 'Value3'}{'key1': 'newvalue', 'key2': 'Value2', 'key3': 'Value3'}{'key1': 'Value1', 'key2': 'Value2', 'key3': 'Value3'}