python tutorial - Python dictionary comprehension with zip from list - learn python - python programming
Dictionary construction with zip
- We can use zip to generate dictionaries when the keys and values must be computed at runtime.
- In general, we can make a dictionary by typing in the dictionary literals:
- Or we can make it by assigning values to keys:
- However, there are cases when we get the keys and values in lists at runtime. For instance like this:
How can we construct a dictionary from those lists of keys and values ?
- Now it's time to use zip. First, we zip the lists and loop through them in parallel like this:
- Note that making a dictionary like that only works for Python 3.x.
- There is another way of constructing a dictionary via zip that's working for both Python 2.x and 3.x. We make a dict from zip result:
- Python 3.x introduced dictionary comprehension, and we'll see how it handles the similar case.
Dictionary Comprehension
- As in the previous section, we have two lists:
- Now we use dictionary comprehension (Python 3.x) to make dictionary from those two lists:
- It seems require more code than just doing this:
- However, there are more cases when we can utilize the dictionary comprehension. For instance, we can construct dictionary from one list using comprehension:
- When we want initialize a dict from keys, we do this:
- We can use dictionary comprehension to do the same thing;
- We sometimes generate a dict by iterating each element:
- If we use comprehension:
Simple zip()
- The following example calculates Hamming distance. Hamming distance is the number of positions at which the corresponding symbols are different. It's defined for two strings of equal length.
Conditional zip()
- The same thing can be done using NumPy's where: