Python Dictionary
A dictionary in Python is an unordered collection of key-value pairs, enclosed in curly braces {}, where each key is unique and mapped to a corresponding value. Dictionaries are mutable and versatile, allowing efficient lookup, insertion, deletion, and iteration over keys and values.
#Python Dictionary
#Dictionary is a collection which is ordered** and changeable. No duplicate members.
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
#Dictionary length
print("Length : ",len(thisdict))
#Get items
print("All values : ",thisdict)
print("Single Item : ",thisdict["brand"])
# change items
thisdict["year"] = 2020
print("After change : ",thisdict)
#add items
thisdict["color"] = "red"
print("After add : ",thisdict)
#Remove items
thisdict.pop("model")
print("After remove : ",thisdict)
#check item
print("Checking an item in dictionary:")
if "model" in thisdict:
print("Yes, 'model' is one of the keys in the thisdict dictionary")
#loop dictionary
#keys only
print("Loop keys only:-")
for x in thisdict:
print(x)
#values only
print("Loop values only:-")
for x in thisdict:
print(thisdict[x])
#print keys and values
print("Loop keys and values:-")
for x, y in thisdict.items():
print(x, y)
Python Online Compiler