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

Click to Enlarge


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

Click to Enlarge


Clear all items from 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

Click to Enlarge


Loop through all key-value pair in 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

Click to Enlarge


Uniqueness of element in dictionary




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




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

Click to Enlarge


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

Click to Enlarge


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

Click to Enlarge


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