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"])





Click to Enlarge


Delete from the dictionary




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

print(personInformation)


# Delete Key from dictionary

del personInformation ["Age"]

print(personInformation)





Click to Enlarge


Clear all items from dictionary




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

print(personInformation)

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





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)





Click to Enlarge


Uniqueness of element in dictionary




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





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"])





Click to Enlarge


Posted By  -  Karan Gupta
 
Posted On  -  Thursday, February 14, 2019
 
Updated On  -  Friday, March 29, 2019

Query/Feedback


Your Email Id  
 
Subject 
 
Query/FeedbackCharacters remaining 250