Python Dictionary

Definition

A Python dictionary is the 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 with "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'}
Value1
Value2

Updating Dictionary


We can add more key-value pairs in a dictionary, change 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 rum 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

True
True
False

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 mydict
print(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 = mydict
print(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'}



Read More:


  • YouTube Video Downloader Using Python
    This is just a two-line program but to convert it to GUI YouTube Video Downloader is a bit longer still, this program of GUI YouTube Video Downloader is less than 25 lines. But still, if you want that two-line program then click here. We have explained this program in every line to make it understand…
  • Word Mix in Python | Assignment Expert
    Problem Statement: We are given a sentence, we need to word mix in Python means we need to mix the words of the sentence such that new words get formed. How? We need to select a letter from each word from the same index. If there is no letter in the word, do nothing and…
  • WHY YOU NEED HAND WRITTEN NOTES?
    Handwritten notes are very important while learning any new programming language. WHO AM I? Owner of Python.hub Instagram Page with more than 1.2 million followers. Running this website copyassignment.com which helps in learning programming. Helped more than 3000 people with their projects and doubts. Running a freelancing IT business and helping startups in building their…
  • Why Learn Python? |Explained|
            Why Learn Python? complete explanation-> Nowadays, we all are wondering through our sights, imagination, and thoughts about the scenario after and along in this pandemic time! But, Yes, ‘Learning doesn’t stop and it Shouldn’t!’, right?  So, in this article, we will found the answer to “Why Learn Python?”.                There are a lot of…
  • Why are pre-cleaning steps important to complete prior to data cleaning?
    Data cleaning is the process of ensuring data is correct, consistent, and usable. You can clean data by identifying errors or corruptions, correcting or deleting them, or manually processing data as needed to prevent the same errors from occurring. The quality of data will have a huge impact on the quality of the model. Data…


2 thoughts on “Python Dictionary

Comments are closed.