Articles → Python → Dictionary In Python

Dictionary In Python






What Is A Dictionary?





Syntax


Variable_name  = {“key name1”: value1, “key name 2: value 2………….}




Variable_name[“key name”]

Example




personInformation = {"Name": "Karan", "Age":37}

print(personInformation)

print(personInformation["Name"])




Picture showing your first dictionary in python



Delete From The Dictionary




personInformation = {"Name": "Karan", "Age":37}

print(personInformation)


# Delete Key from dictionary

del personInformation ["Age"]

print(personInformation)




Picture showing the dictionary after deleting the Age key from it



Clear All Items From The Dictionary




personInformation = {"Name": "Karan", "Age":37}

print(personInformation)

# Clear all items from dictionary
personInformation.clear()
print(personInformation)




Picture showing the dictionary after clearing all items from it



Loop Through All Key-Value Pair In The Dictionary




personInformation = {"Name": "Karan", "Age":37}

for k,v in personInformation.items():
        print("Key:",k,", Value:",v)




Picture showing the output of Loop through all key-value pair in dictionary



The Uniqueness Of Elements In The Dictionary




dict = {"key1":1, "key1":2}
print(dict)




Picture shows how the print function in python removes duplicacy of keys in the dictionary



Nested Dictionary




nested_dictionary = {"name": "Karan", "address": {"city":"Gurgaon", "country": "India"}}
                         

print("Name:", nested_dictionary["name"])
print("city:", nested_dictionary["address"]["city"])
print("country:", nested_dictionary["address"]["country"])




Picture showing the nested dictionary in python



Delete The Whole Dictionary




personInformation = {"Name": "Karan", "Age":37}


print(personInformation)

del(personInformation)

print(personInformation)




Picture showing the error message as the code is trying to print the deleted dictionary



Posted By  -  Karan Gupta
 
Posted On  -  Thursday, February 14, 2019
 
Updated On  -  Saturday, September 25, 2021

Query/Feedback


Your Email Id
 
Subject
 
Query/FeedbackCharacters remaining 250