Python Dictionary:
A dictionary is a collection of items which is not in order, changeable and are indexed.
In Python dictionary are written with curly brackets and they have keys and values.
Example:
dict1 = {
"brand": "BMW",
"color": "Red",
"year": 2009
}
print(dict1)
Output:
{'brand': 'BMW', 'color': 'Red', 'year': '2009'}
Accessing Items in dict:
Example:
dict1 = {
"brand": "BMW",
"color": "Red",
"year": 2009
}
print(x)
Output:
BMW
Note: Here we have access item with the help of their key name.
Output:
BMW
Note: Here we have access item with the help of their key name.
(x = dict1["brand"])
Changing values in dict:
Example:
dict1 = {
"brand": "BMW",
"color": "Red",
"year": 2009
}
print(x)
Output:
{'brand': 'BMW', 'color': 'Red', 'year': '2019'}
For loop through a dict:
Example:
dict1 = {
"brand": "BMW",
"color": "Red",
"year": 2009
}
print(x)
Output:
brand
color
year
To print all values of dictionary:
Example:
dict1 = {
"brand": "BMW",
"color": "Red",
"year": 2009
}
print(dict1[x])
Output:
BMW
Red
2019
Note: In above example,we can use [for x in dict1.values()] instead of
[for x in dict1].
To print both key and value:
Example:
dict1 = {
"brand": "BMW",
"color": "Red",
"year": 2009
}
print(x,y)
Output:
brand BMW
color Red
year 2019
Dictionary Length:
Example:
dict1 = {
"brand": "BMW",
"color": "Red",
"year": 2009
}
print(len(dict1))
Output:
3
Output:
3
Adding Items to dict:
Example:
dict1 = {
"brand": "BMW",
"color": "Red",
"year": 2009
}
dict1['speed'] = "fast"
dict1['speed'] = "fast"
print(dict1)
Output:
{'brand': 'BMW', 'color': 'Red', 'year': '2009', 'speed': 'fast'}
Removing Items from dict:
pop()
method is used to remove item.
Example:
dict1 = {
"brand": "BMW",
"color": "Red",
"year": 2009
}
dict1.pop("color")
print(dict1)
Output:
Output:
{'brand': 'BMW', 'year': '2009'}
Note: we can also use (del dict1["color"]) instead of [dict1.pop("color")] to remove specific key.
clear( ) method:
Example:
dict1 = {
"brand": "BMW",
"color": "Red",
"year": 2009
}
dict1.clear()
print(dict1)
Output:
{}
Note: clear() method clear the dictionary.
Copy a Dictionary:
copy()
method is used to copy a dictionary into another.
Example:
dict1 = {
"brand": "BMW",
"color": "Red",
"year": 2009
}
dict2 = dict1.copy()
print(dict2)
Output:
{'brand': 'BMW', 'color': 'Red', 'year': '2009'}
dict( ) Constructor:
dict() constructor to make a new dictionary.
Example:
dict1 = dict("brand": "BMW","color": "Red","year": 2009)
print(dict1)
Output:
{'brand': 'BMW', 'color': 'Red', 'year': '2009'}
fromkeys() method:
fromkeys()
method returns a dictionary with the specified keys and values.
Example:
x = ('brand', 'color', 'year')
y = ('BMW', 'Red', '2009')
y = ('BMW', 'Red', '2009')
dict1 = dict.fromkeys(x, y)
print(thisdict)
Output:
{'brand': 'BMW', 'color': 'Red',': '2009'}
keys() method:
Example:
dict1 = {
"brand": "BMW",
"color": "Red",
"year": 2009
}
x = dict1.keys()
print(x)
Output:
('brand', 'color', 'year')
Output:
('brand', 'color', 'year')
0 Comments