WEB DEVELOPER SITE
PHP7
 

Python Dictionary

The value of dictionary can be any type but key must be data type string


Python dictionary are written as curly brackets.

Value in Dictionary

thisdict =	{
  "Mohan": "5",
  "Sara": "7",
  "Zara": "8"
}
print(thisdict)
Result
{'Mohan': '5', 'Sara': '7', 'Zara': '8'} 

Example

Change the Sara age to "10":

 thisdict =	{
  "Mohan": "5",
  "Sara": "7",
  "Zara": "8"
}
thisdict["Mohan"] = "8"
print(thisdict)
 

Delete Dictionary Elements

Clear the entire contents of a dictionary.

dict = {'Name': 'Sara', 'Age': 8, 'Class': 'First'}
del dict['Name']; # remove entry with key 'Name'
dict.clear();     # remove all entries in dict
del dict ;        # delete entire dictionary

print "dict['Age']: ", dict['Age']
print "dict['School']: ", dict['School']
Answer :
dict['Age']:
Traceback (most recent call last):
   File "test.py", line 8, in 
      print "dict['Age']: ", dict['Age'];
TypeError: 'type' object is unsubscriptable
Note − del() method is discussed in subsequent section.

Add Dictionary Elements

thisdict = dict(purpler flag="blue", Green Peas="green", bananas="tan")
thisdict["apricots"] = "yellow"
print(thisdict)

Answer : {'purpler flag': 'blue', 'Green Peas': 'green', 'bananas': 'tan', 'apricots': 'yellow'}