Topics:
1. Python Collections
2. Dictionaries
3. Dictionary Length
4. Dictionary Items Data Types
5. Accessing Dictionary Items
6. Get Dictionary Keys
7. Get Dictionary Values
8. Get Dictionary Items
9. Check if Dictionary Key Exists
10. Change Dictionary Values
11. Update Dictionary Values
12. Add Dictionary Items
13. Remove Dictionary Items
14. Loop through Dictionary
15. Copy a Dictionary
16. Nested Dictionaries
17. Dictionary fromkeys() Method
18. Dictionary setdefault() Method
19. Dictionary List pairing
20. Dictionary List pairing with Zip
21. Dictionary List pairing with Zip_longest
1. Python Collections
>>Return to Menu
There are four collection data types in the Python programming language:
- List is a collection which is ordered and changeable. Allows duplicate members.
- Tuple is a collection which is ordered and unchangeable. Allows duplicate members.
- Set is a collection which is unordered, unchangeable, and unindexed. No duplicate members.
- Dictionary is a collection which is ordered and changeable. No duplicate members.
2. Dictionaries
>>Return to Menu
A dictionary is a collection which is ordered, changeable and do not allow duplicates.
- Dictionaries are ordered, meaning that the items have a defined order, and that order will not change.
- Dictionaries are changeable, meaning that we can change, add or remove items after the dictionary has been created.
- Dictionaries cannot have two items with the same key.
Dictionary items are presented in key:value pairs, and can be referred to by using the key name.
student = {
"name": "Paul",
"age": 32,
"year of graduation": 2020
}
print(student)
student = {
"name": "Paul",
"age": 32,
"year of graduation": 2020
}
print(student['name'])
3. Dictionary Length
>>Return to Menu
Use the len() function to determine how many items a dictionary has.
student = {
"name": "Paul",
"age": 32,
"year of graduation": 2020
}
print(len(student))
4. Dictionary Items Data Types
>>Return to Menu
mydict = {
"brand": "Ford",
"electric": False,
"year": 1964,
"colors": ["red", "white", "blue"]
}
print(type(mydict['brand']))
print(type(mydict['electric']))
print(type(mydict['year']))
print(type(mydict['colors']))
print(type(mydict))
5. Accessing Dictionary Items
>>Return to Menu
mydict = {
"brand": "Ford",
"electric": False,
"year": 1964,
"colors": ["red", "white", "blue"]
}
print(mydict.get('year'))
print(mydict['colors'])
6. Get Dictionary Keys
>>Return to Menu
The keys() method will return a list of all the keys in the dictionary.
mydict = {
"brand": "Ford",
"electric": False,
"year": 1964,
"colors": ["red", "white", "blue"]
}
print(mydict.keys())
for index,key in enumerate(mydict.keys()):
print(index,key)
7. Get Dictionary Values
>>Return to Menu
mydict = {
"brand": "Ford",
"electric": False,
"year": 1964,
"colors": ["red", "white", "blue"]
}
print(mydict.values())
for index,value in enumerate(mydict.values()):
print(index,value)
8. Get Dictionary Items
>>Return to Menu
mydict = {
"brand": "Ford",
"electric": False,
"year": 1964,
"colors": ["red", "white", "blue"]
}
print(mydict.items())
for index,item in enumerate(mydict.items()):
print(index,item)
9. Check if Dictionary Key Exists
>>Return to Menu
mydict = {
"brand": "Ford",
"electric": False,
"year": 1964,
"colors": ["red", "white", "blue"]
}
if 'year' in mydict:
print(f"The value of key (year) is {mydict.get('year')}.")
else:
print('year is not a key in mydict.')
10. Change Dictionary Values
>>Return to Menu
mydict = {
"brand": "Ford",
"electric": False,
"year": 1964,
"colors": ["red", "white", "blue"]
}
mydict['year'] = 2001
for item in mydict.items():
print(item)
11. Update Dictionary Values
>>Return to Menu
mydict = {
"brand": "Ford",
"electric": False,
"year": 1964,
"colors": ["red", "white", "blue"]
}
mydict.update({'brand':'Tesla','colors':["black","white"]})
for item in mydict.items():
print(item)
12. Add Dictionary Items
>>Return to Menu
Adding an item to the dictionary is done by using a new index key and assigning a value to it.
mydict = {
"brand": "Ford",
"electric": False,
"year": 1964,
"colors": ["red", "white", "blue"]
}
mydict['is_new'] = True
mydict.update({'rating':8})
for item in mydict.items():
print(item)
13. Remove Dictionary Items
>>Return to Menu
- The pop() method removes the item with the specified key name.
- The popitem() method removes the last inserted item.
- The del keyword removes the item with the specified key name.
- The clear() method empties the dictionary.
mydict = {
"brand": "Ford",
"electric": False,
"year": 1964,
"colors": ["red", "white", "blue"],
"is_new": True,
"rating": 8
}
print('#popitem() --> "rating"')
mydict.popitem()
print('#pop() --> "colors"')
mydict.pop('colors')
print('#del --> "is_new"')
del mydict['is_new']
print('#clear() --> empty_dict')
mydict.clear()
14. Loop through Dictionary
>>Return to Menu
When looping through a dictionary, the return value are the keys of the dictionary, but there are methods to return the values as well.
mydict = {
"brand": "Ford",
"electric": False,
"year": 1964,
"colors": ["red", "white", "blue"],
"is_new": True,
"rating": 8
}
for x in mydict:
print(x)
mydict = {
"brand": "Ford",
"electric": False,
"year": 1964,
"colors": ["red", "white", "blue"],
"is_new": True,
"rating": 8
}
for x in mydict:
print(mydict[x])
Loop through both keys and values, by using the items() method:
mydict = {
"brand": "Ford",
"electric": False,
"year": 1964,
"colors": ["red", "white", "blue"],
"is_new": True,
"rating": 8
}
for key, value in mydict.items():
print(key, value)
15. Copy a Dictionary
>>Return to Menu
mydict = {
"brand": "Ford",
"electric": False,
"year": 1964,
"colors": ["red", "white", "blue"],
"is_new": True,
"rating": 8
}
thisdict = mydict.copy()
print(thisdict)
mydict = {
"brand": "Ford",
"electric": False,
"year": 1964,
"colors": ["red", "white", "blue"],
"is_new": True,
"rating": 8
}
thisdict = dict(mydict)
print(thisdict)
16. Nested Dictionaries
>>Return to Menu
classA = {
"student1" : {
"name" : "Schum",
"age" : 20
},
"student2" : {
"name" : "Toby",
"age" : 17
},
"student3" : {
"name" : "Jake",
"age" : 23
}
}
print(classA)
17. Dictionary fromkeys() Method
>>Return to Menu
x = ('key1', 'key2', 'key3')
y = 10
mydict = dict.fromkeys(x, y)
print(mydict)
x = ('key1', 'key2', 'key3')
mydict = dict.fromkeys(x)
print(mydict)
18. Dictionary setdefault() Method
>>Return to Menu
The setdefault() method returns the value of the item with the specified key. If the key does not exist, insert the key, with the specified value.
Get the value of the "color" item, if the "color" item does not exist, insert "color" with the value "white":
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = car.setdefault("color", "white")
print(x)
print(car)
19. Dictionary List pairing
>>Return to Menu
students = ["James","Bond","Mary","Samson","Prof"]
scores = [48,72,91]
dict_student = {students[i]:scores[i] for i in range(len(scores))}
print(dict_student)
20. Dictionary List pairing with Zip
>>Return to Menu
students = ["James","Bond","Mary","Samson","Prof"]
scores = [48,72,91]
dict_student = zip(students,scores)
print(dict_student)
dict_student = list(zip(students,scores))
print(dict_student)
dict_student = {i:j for i,j in list(zip(students,scores))}
print(dict_student)
dict_student = dict(zip(students,scores))
print(dict_student)
21. Dictionary List pairing with Zip_longest
>>Return to Menu
import itertools
students = ["James","Bond","Mary","Samson","Prof"]
scores = [48,72,91]
dict_student = itertools.zip_longest(students,scores)
print(dict_student)
dict_student = dict(itertools.zip_longest(students,scores))
print(dict_student)
#End
Hope you enjoyed this! :) Follow me for more contents...
Get in Touch:
ifeanyiomeata.com
contact@ifeanyiomeata.com
Youtube: youtube.com/c/IfeanyiOmeata
Linkedin: linkedin.com/in/omeatai
Twitter: twitter.com/iomeata
Github: github.com/omeatai
Stackoverflow: stackoverflow.com/users/2689166/omeatai
Hashnode: hashnode.com/@omeatai
Medium: medium.com/@omeatai
© 2022