Python Dictionary
Dictionary is unordered,changable and indexed collection of items.
Create a Dictionary
In Python,dictionaries are written with curly brackets and they have keys and values pair.
Example
thisdict={ "brand":"Ford", "model":"Mustang", "year":1964 } print(thisdict) Output {'brand','Ford','model','Mustang','year','1964'}
Access Dictionary Elements
We can access the items of a dictionary by referring to its key name,inside square brackets.
Example
thisdict={
"brand":"Ford",
"model":"Mustang",
"year":1964
}
print(thisdict["model"])
Output
{'brand','Ford','model','Mustang','year','1964'}
Loop through Dictionary
We can loop through the dictionary items by using a for loop.
When looping through dictionary the return values are the keys of dictionary,but there are methods to return the values as well.
Example
thisdict={
"brand":"Ford",
"model":"Mustang",
"year":1964
}
for x in thisdict:
print(x)
Output
{'brand','Ford','model','Mustang','year','1964'}
Example
thisdict={ "brand":"Ford", "model":"Mustang", "year":1964 } for x in thisdict.values(): print(x) Output {'brand','Ford','model','Mustang','year','1964'}
Loop through both keys and values using the items()
function.
Example
thisdict={ "brand":"Ford", "model":"Mustang", "year":1964 } for x,y in thisdict.values(): print(x,y) Output {'brand','Ford','model','Mustang','year','1964'}
Dictionary Length
To determine how many items a dictionary has, use the len()
function.
Example
thisdict={ "brand":"Ford", "model":"Mustang", "year":1964 } print(len(thisdict)) Output {'brand','Ford','model','Mustang','year','1964'}
Add Items in Dictionary
- To add an item to the dictionary,we use a new index key and assigning a value to it.
Example
thisdict={ "brand":"Ford", "model":"Mustang", "year":1964 } thisdict["color"]="Red" print(thisdict) Output {'brand','Ford','model','Mustang','year':1964 ,'color':'red'}
Remove Items in Dictionary
The pop() method removes the item with the specified key name.
Example
thisdict={ "brand":"Ford", "model":"Mustang", "year":1964 } thisdict.pop("model") print(thisdict) Output {'brand','Ford','year':1964}
The popitem()
method removes the last inserted item.
Example
thisdict={ "brand":"Ford", "model":"Mustang", "year":1964 } thisdict.popitem() print(thisdict) Output {'brand','Ford','model','Mustang'}
Dictionary Constructor
Using dict()
constructor,we can make a set.
Example
thisdict=dict(brand="Ford",model="Mustang",year=1964) print(thisdict) Output {'brand','Ford','model','Mustang','year:1964}