Python Dictionary

Dictionary

Dictionary is a collection of unordered items separated by comma and enclosed within curly brackets.

Items in dictionary have Key and value separated by a colon and they are mutable.

Dictionaries are indexed and do not allow duplicate items.

bodyPropdict = {"Bname" : "head", "Faces" : 10, "Edges" : 25 }
print(bodyPropdict)
Output
{'Faces': 10, 'Edges': 25, 'Bname': 'head'}

Use len() method to find the number of items in the dictionary.

Add items

bodyPropdict = {"Bname" : "head", "Faces" : 10, "Edges" : 25 }
bodyPropdict["Vertex"] = 8
print(bodyPropdict)
Output
{'Vertex': 8, 'Faces': 10, 'Edges': 25, 'Bname': 'head'}

Remove Items

pop()

removes the item with the specified key.

bodyPropdict = {"Bname" : "head", "Faces" : 10, "Edges" : 25 }
bodyPropdict.pop("Faces")
print(bodyPropdict)
Output
{'Edges': 25, 'Bname': 'head'}

Delete Dictionary or Items

bodyPropdict = {"Bname" : "head", "Faces" : 10, "Edges" : 25 }
del bodyPropdict["Faces"]
print(bodyPropdict)
del bodyPropdict
Output
{'Edges': 25, 'Bname': 'head'}

Clear Dictionary

empties the dictionary.

bodyPropdict = {"Bname" : "head", "Faces" : 10, "Edges" : 25 }
bodyPropdict.clear()
print(bodyPropdict)
Output
{}

Copy Dictionary

Copies the items in the dictionary to another dictionary.

copy()

bodyPropdict = {"Bname" : "head", "Faces" : 10, "Edges" : 25 }
blockDict = bodyPropdict.copy()
print(blockDict)
Output
{'Faces': 10, 'Edges': 25, 'Bname': 'head'}

dict()

bodyPropdict = {"Bname" : "head", "Faces" : 10, "Edges" : 25 }
blockDict = dict(bodyPropdict)
print(blockDict)
Output
{'Faces': 10, 'Edges': 25, 'Bname': 'head'}

Dictionary Trasversal

Access Keys

bodyPropdict = {"Bname" : "head","Faces" : 10,"Edges" : 25}
for e in bodyPropdict:
	print(e)
Output
Faces
Edges
Bname

Access Values

bodyPropdict = {"Bname" : "head","Faces" : 10,"Edges" : 25}
for e in bodyPropdict:
	print(bodyPropdict[e])
Output
10
25
head

Using values() method

bodyPropdict = {"Bname" : "head","Faces" : 10,"Edges" : 25}
for e in bodyPropdict.values():
	print(e)
Output
10
25
head

Access Keys and Values

Using items() method

bodyPropdict = {"Bname" : "head","Faces" : 10,"Edges" : 25}
for k,v in bodyPropdict.items():
	print(k,v)
Output
Faces 10
Edges 25
Bname head

Check Dictionary for a Key

bodyPropdict = {"Bname" : "head","Faces" : 10,"Edges" : 25}
if "Faces" in bodyPropdict:
	print("Key Found")
Output
Key Found