Python Dictionary¶
Dictionaries are used to store data values in key:value pairs. A dictionary is a collection which is ordered*, changeable and does not allow duplicates. Dictionaries are written with curly brackets, and have keys and values: {‘Key’:’Value’}
Note:As of Python version 3.7, dictionaries are ordered. In Python 3.6 and earlier, dictionaries are unordered.
D = {}
print(D)
D = {'Name':'Kevin','Age':30,'Marks':89.78}
print(D)
print(D['Name'])
print(D['Age'])
print(D['Marks'])
Duplicates Not Allowed¶
- Dictionaries cannot have two items with the same key and Duplicate values will overwrite existing values:
D = {'Name':'Kevin','Age':30,'Marks':89.78,'Age':56}
print(D)
Dictionary Length and Type¶
print(D)
print(len(D))
print(type(D))
Dictionary Items¶
- The values in dictionary items can be of any data type:
D = {
"brand": "Tesla",
"electric": True,
"year": 2021,
"colors": ["black", "white", "red"]
}
print(D)
Accessing Items¶
print(D)
print(D['brand'])
There is also a method called get() that will give you the same result:
print(D.get('brand'))
Get all Keys¶
print(D.keys())
Get all Values¶
print(D.values())
The list of the keys is a view of the dictionary, meaning that any changes done to the dictionary will be reflected in the keys list.
car = {
"brand": "Tesla",
"electric": True,
"year": 2021,
}
x = car.keys()
print(x) #before the change
car["color"] = "black"
print(x) #after the change
Make a change in the original dictionary, and see that the values list gets updated as well:
car = {
"brand": "Tesla",
"electric": True,
"year": 2021,
}
x = car.values()
print(x) #before the change
car["color"] = "black"
print(x) #after the change
Get Items¶
- The items() method will return each item in a dictionary, as tuples in a list.
car = {
"brand": "Tesla",
"electric": True,
"year": 2021,
}
print(car.items())
Make a change in the original dictionary, and see that the items list gets updated as well:
car = {
"brand": "Tesla",
"electric": True,
"year": 2021,
}
x = car.items()
print(x) #before the change
car["color"] = "black"
print(x) #after the change
Check if Key Exists¶
- To determine if a specified key is present in a dictionary use the in keyword:
car = {
"brand": "Tesla",
"electric": True,
"year": 2021,
}
if "brand" in car:
print("Yes, 'brand' is one of the keys in the car dictionary")
Change Dictionary Items¶
car = {
"brand": "Tesla",
"electric": True,
"year": 2021,
"color": 'black'
}
print(car)
car['color'] = 'white'
print(car)
Update the “year” of the car by using the update() method:¶
car.update({"year": 2022})
print(car)
Add Dictionary Items¶
car = {
"brand": "Tesla",
"electric": True,
"year": 2021,
}
print(car)
car['color'] = 'black'
print(car)
Update Dictionary¶
- The update() method will update the dictionary with the items from a given argument. If the item does not exist, the item will be added.
- The argument must be a dictionary, or an iterable object with key:value pairs.
car = {
"brand": "Tesla",
"electric": True,
"year": 2021
}
print(car)
car.update({"color": "black"})
print(car)
Remove Dictionary Items¶
- The pop() method removes the item with the specified key name:
print(car)
car.pop('electric')
print(car)
The del keyword removes the item with the specified key name:¶
print(car)
del car['year']
print(car)
The del keyword can also delete the dictionary completely:
del car
print(car)
The clear() method empties the dictionary:¶
car = {
"brand": "Tesla",
"electric": True,
"year": 2021
}
car.clear()
print(car)
Loop Through a Dictionary¶
- You can loop through a dictionary by using a for loop.
- When looping through a dictionary, the return value are the keys of the dictionary, but there are methods to return the values as well.
car = {
"brand": "Tesla",
"electric": True,
"year": 2021
}
for i in car:
print(i)
Print all values in the dictionary, one by one:¶
for i in car:
print(car[i])
You can also use the values() method to return values of a dictionary:¶
for i in car.values():
print(i)
You can use the keys() method to return the keys of a dictionary:¶
for i in car.keys():
print(i)
Loop through both keys and values, by using the items() method:¶
for i in car.items():
print(i)
for i,j in car.items():
print(i,j)
Copy a Dictionary¶
- You cannot copy a dictionary simply by typing dict2 = dict1, because: dict2 will only be a reference to dict1, and changes made in dict1 will automatically also be made in dict2.
- There are ways to make a copy, one way is to use the built-in Dictionary method copy().
car = {
"brand": "Tesla",
"electric": True,
"year": 2021
}
car2 = car
print(car)
print(car2)
car['year']=2022
print(car)
print(car2)
car = {
"brand": "Tesla",
"electric": True,
"year": 2021
}
car2 = car.copy()
print(car)
print(car2)
car['year']=2022
print(car)
print(car2)
Nested Dictionary¶
myfamily = {
"child1" : {
"name" : "Kevin",
"year" : 2009
},
"child2" : {
"name" : "Ronaldo",
"year" : 2011
},
"child3" : {
"name" : "Keisha",
"year" : 2013
}
}
print(myfamily)
print(myfamily['child1'])
print(myfamily['child1']['name'])
print(myfamily['child1']['year'])
Dictionary of a list¶
d={'Name':['Kevin','Ranaldo','Keisha'],'Age':[31,33,34]}
print(d)
print(d['Name'])
print(d['Age'])
print(d.keys())
print(d.values())
print(d.items())
for i,j in d.items():
print(i,j)
for i,j in d.items():
print("Key:",i)
for val in j:
print(val)
print()