A dictionary is a collection which is unordered, changeable and indexed. In Python dictionaries are written with curly brackets, and they have keys and values.
Create and print a dictionary:
dict ={"brand": "Ford","model": "Mustang","year": 1964}
print(dict)
Output:
{'brand': 'Ford', 'model': 'Mustang', 'year': 1964}
You can access the elements of a dictionary by referring to its key name, inside square brackets:
dict ={"brand": "Ford","model": "Mustang","year": 1964}
x = dict["model"]
print(x)
Output:
Mustang
You can change the value of a specific item by referring to its key name:
Change the "year" to 2018:
dict ={"brand": "Ford","model": "Mustang","year": 1964}
dict["year"] = 2019
Output:
{'brand': 'Ford', 'model': 'Mustang', 'year': 2019}
2.8.3 Display Using Loop:
dict ={"brand": "Ford","model": "Mustang","year": 1964}
for x in dict:
print(x)
Output:
Brand
Model
Year
Print all values in the dictionary, one by one:
dict ={"brand": "Ford","model": "Mustang","year": 1964}
for x in dict:
print(dict[x])
Output:
Ford
Mustang
1964
dict ={"brand": "Ford","model": "Mustang","year": 1964,"color":"red"}
dict["color"] = "red"
print(dict)
Output:
{"brand": "Ford","model": "Mustang","year": 1964,"color":"red"}