We are adding this chapter as a reference to help you read existing programs.
A dictionary consists of pairs of keys, and values. A standard way to initialize a dictionary is to combine its keys and values with zip.
# Using zip() in Python
numbers = [1, 2, 3]
letters = ['a', 'b', 'c']
zipped = zip(numbers, letters)
for values in zipped:
print(values)
# Output
# (1, 'a')
# (2, 'b')
# (3, 'c')
A standard way to initialize a dictionary is to combine its keys and values with zip, and pass the result to the dict() function. However, you can achieve the same result with a dictionary comprehension.
keys = ['name', 'age', 'job']
values = ['Bob', '24', 'Devel']
# Using dict comprehension
myDict = {k: v for (k,v) in zip(keys,values)}
print(myDict)
# Output {'name': 'Bob', 'age': '24', 'job': 'Devel'}
# Equivalent to using dict() on zipped keys/values
myDict = dict(zip(keys, values))
print(myDict)
# Output {'name': 'Bob', 'age': '24', 'job': 'Devel'}
Sometimes we need to create a dictionary of keys to numbers. We will use the command enumerate to combine the provided keys with integer numbers.
keys = ['name', 'age', 'job']
values = ['Bob', '24', 'Devel']
# Create a dictionary of keys to numbers
char_to_int = dict((c, i) for i, c in enumerate(keys))
print(char_to_int)
# Output {'name': 0, 'age': 1, 'job': 2}
Table of Contents
Ch1-Install Python
Ch2-Install PyCharm
Ch3-Save Work
Ch4-Add Project
Ch5-Variables
Ch6-Print&Input
Ch7-Lists
Ch8-Loops
Ch9-If&Logical
Ch10-Functions
Ch11-Bubble Sort
Ch12-Plotting
Ch13-Files
Ch14-Print Format
Ch15-Dict&Comp&Zip
Ch16-Arrays
Ch17-Electrical
Ch18-Regression
Ch19-Differential
Ch20-Secant