Python Devlopment






Dictionaries



2.8 Python Dictionaries:

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.

Example

Create and print a dictionary:

dict ={"brand": "Ford","model": "Mustang","year": 1964}
print(dict)

Output: 
    {'brand': 'Ford', 'model': 'Mustang', 'year': 1964}

2.8.1 Accessing Elements:

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

2.8.2 Change Values:

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

Example

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

 

2.8.4 Adding Elements:

 

dict ={"brand": "Ford","model": "Mustang","year": 1964,"color":"red"}
dict["color"] = "red"
print(dict)

Output:    
{"brand": "Ford","model": "Mustang","year": 1964,"color":"red"}