Python Dictionary tutorial - Basics of how to use Python dictionary

Dictionary is very powerful in-built data type in Python which are essentially key value pairs.  

Syntax of a dictionary - {'key':'value' } 

Sample dictionary - student = {"name":"Gaurang"}

Iterating over in the dictionary -

for k,v in student.items():
    print("Name is",k,"and", "Value is",v)
print(student)

To access value of a dictionary - 

print(student['name']) 

Gaurang - #this returns the value of the key from the dictionary variable name called Student. 

 

#To delete the items of a dictionary, use clear()

student.clear()
for k,v in student.items():
    print("Name is",k,"and", "Value is",v)
print(student)

 

Dictionary Methods

  • dict.get(key, default) – Safe value access.

  • dict.keys() – All keys.

  • dict.values() – All values.

  • dict.items() – All key-value pairs.

  • dict.update(other_dict) – Merge dictionaries.

  • dict.pop(key) – Remove a key and return its value.

  • dict.clear() – Remove all items.