Dictionary Comprehension
[xv if c else yv for (c,xv,yv) in zip(condition,x,y)]
Suppose we have two lists, we want to make them a list making pairs with . How can we do that?
>>> a = [1,2,3] >>> b = [4,5,6]
For Python 2.x:
>>> z = zip(a,b) >>> z [(1, 4), (2, 5), (3, 6)]
For Python 3.x:
>>> z = list(zip(a,b)) >>> z [(1, 4), (2, 5), (3, 6)]
Then, we reverse the course, and want to get each list back. How?
>>> c, d = zip(*z) >>> c, d ((1, 2, 3), (4, 5, 6))
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:
>>> D1 = {'a':1, 'b':2, 'c':3} >>> D1 {'a': 1, 'c': 3, 'b': 2} >>>
Or we can make it by assigning values to keys:
>>> D1 = {} >>> D1['a'] = 1 >>> D1['b'] = 2 >>> D1['c'] = 3 >>> D1 {'a': 1, 'c': 3, 'b': 2}
However, there are cases when we get the keys and values in lists at runtime. For instance like this:
>>> keys = ['a', 'b', 'c'] >>> values = [1, 2, 3]
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:
>>> list(zip(keys,values)) [('a', 1), ('b', 2), ('c', 3)] >>> D2 = {} >>> for (k,v) in zip(keys, values): ... D2[k] = v ... >>> D2 {'a': 1, 'b': 2, 'c': 3}
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:
>>> D3 = dict(zip(keys, values)) >>> D3 {'a': 1, 'b': 2, 'c': 3}
Python 3.x introduced dictionary comprehension, and we'll see how it handles the similar case. Let's move to the next section.
As in the previous section, we have two lists:
>>> keys = ['a', 'b', 'c'] >>> values = [1, 2, 3]
Now we use dictionary comprehension (Python 3.x) to make dictionary from those two lists:
>>> D = { k:v for (k,v) in zip(keys, values)} >>> D {'a': 1, 'b': 2, 'c': 3}
It seems require more code than just doing this:
>>> D = dict(zip(keys, values)) >>> D {'a': 1, 'b': 2, 'c': 3}
However, there are more cases when we can utilize the dictionary comprehension. For instance, we can construct dictionary from one list using comprehension:
>>> D = {x: x**2 for x in [1,2,3,4,5]} >>> D {1: 1, 2: 4, 3: 9, 4: 16, 5: 25} >>> D = {x.upper(): x*3 for x in 'abcd'} >>> D {'A': 'aaa', 'C': 'ccc', 'B': 'bbb', 'D': 'ddd'}
When we want initialize a dict from keys, we do this:
>>> D = dict.fromkeys(['a','b','c'], 0) >>> D {'a': 0, 'c': 0, 'b': 0}
We can use dictionary comprehension to do the same thing;
>>> D = {k: 0 for k in ['a','b','c']} >>> D {'a': 0, 'c': 0, 'b': 0}
We sometimes generate a dict by iterating each element:
>>> D = dict.fromkeys('dictionary') >>> D {'a': None, 'c': None, 'd': None, 'i': None, 'o': None, 'n': None, 'r': None, 't': None, 'y': None}
If we use comprehension:
>>> D = {k:None for k in 'dictionary'} >>> D {'a': None, 'c': None, 'd': None, 'i': None, 'o': None, 'n': None, 'r': None, 't': None, 'y': None}
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.
def hamming(s1,s2): if len(s1) != len(s2): raise ValueError("Not defined - unequal lenght sequences") return sum(c1 != c2 for c1,c2 in zip(s1,s2)) if __name__ == '__main__': print(hamming('toned', 'roses')) # 3 print(hamming('2173896', '2233796')) # 3 print(hamming('0100101000', '1101010100')) # 6
>>> x = [1,2,3,4,5] >>> y = [11,12,13,14,15] >>> condition = [True,False,True,False,True] >>> [xv if c else yv for (c,xv,yv) in zip(condition,x,y)] [1, 12, 3, 14, 5]
The same thing can be done using NumPy's where:
>>> import numpy as np >>> np.where([1,0,1,0,1], np.arange(1,6), np.arange(11,16)) array([ 1, 12, 3, 14, 5])
Python tutorial
Python Home
Introduction
Running Python Programs (os, sys, import)
Modules and IDLE (Import, Reload, exec)
Object Types - Numbers, Strings, and None
Strings - Escape Sequence, Raw String, and Slicing
Strings - Methods
Formatting Strings - expressions and method calls
Files and os.path
Traversing directories recursively
Subprocess Module
Regular Expressions with Python
Regular Expressions Cheat Sheet
Object Types - Lists
Object Types - Dictionaries and Tuples
Functions def, *args, **kargs
Functions lambda
Built-in Functions
map, filter, and reduce
Decorators
List Comprehension
Sets (union/intersection) and itertools - Jaccard coefficient and shingling to check plagiarism
Hashing (Hash tables and hashlib)
Dictionary Comprehension with zip
The yield keyword
Generator Functions and Expressions
generator.send() method
Iterators
Classes and Instances (__init__, __call__, etc.)
if__name__ == '__main__'
argparse
Exceptions
@static method vs class method
Private attributes and private methods
bits, bytes, bitstring, and constBitStream
json.dump(s) and json.load(s)
Python Object Serialization - pickle and json
Python Object Serialization - yaml and json
Priority queue and heap queue data structure
Graph data structure
Dijkstra's shortest path algorithm
Prim's spanning tree algorithm
Closure
Functional programming in Python
Remote running a local file using ssh
SQLite 3 - A. Connecting to DB, create/drop table, and insert data into a table
SQLite 3 - B. Selecting, updating and deleting data
MongoDB with PyMongo I - Installing MongoDB ...
Python HTTP Web Services - urllib, httplib2
Web scraping with Selenium for checking domain availability
REST API : Http Requests for Humans with Flask
Blog app with Tornado
Multithreading ...
Python Network Programming I - Basic Server / Client : A Basics
Python Network Programming I - Basic Server / Client : B File Transfer
Python Network Programming II - Chat Server / Client
Python Network Programming III - Echo Server using socketserver network framework
Python Network Programming IV - Asynchronous Request Handling : ThreadingMixIn and ForkingMixIn
Python Coding Questions I
Python Coding Questions II
Python Coding Questions III
Python Coding Questions IV
Python Coding Questions V
Python Coding Questions VI
Python Coding Questions VII
Python Coding Questions VIII
Python Coding Questions IX
Python Coding Questions X
Image processing with Python image library Pillow
Python and C++ with SIP
PyDev with Eclipse
Matplotlib
Redis with Python
NumPy array basics A
NumPy Matrix and Linear Algebra
Pandas with NumPy and Matplotlib
Celluar Automata
Batch gradient descent algorithm
Longest Common Substring Algorithm
Python Unit Test - TDD using unittest.TestCase class
Simple tool - Google page ranking by keywords
Google App Hello World
Google App webapp2 and WSGI
Uploading Google App Hello World
Python 2 vs Python 3
virtualenv and virtualenvwrapper
Uploading a big file to AWS S3 using boto module
Scheduled stopping and starting an AWS instance
Cloudera CDH5 - Scheduled stopping and starting services
Removing Cloud Files - Rackspace API with curl and subprocess
Checking if a process is running/hanging and stop/run a scheduled task on Windows
Apache Spark 1.3 with PySpark (Spark Python API) Shell
Apache Spark 1.2 Streaming
bottle 0.12.7 - Fast and simple WSGI-micro framework for small web-applications ...
Flask app with Apache WSGI on Ubuntu14/CentOS7 ...
Fabric - streamlining the use of SSH for application deployment
Ansible Quick Preview - Setting up web servers with Nginx, configure enviroments, and deploy an App
Neural Networks with backpropagation for XOR using one hidden layer
NLP - NLTK (Natural Language Toolkit) ...
RabbitMQ(Message broker server) and Celery(Task queue) ...
OpenCV3 and Matplotlib ...
Simple tool - Concatenating slides using FFmpeg ...
iPython - Signal Processing with NumPy
iPython and Jupyter - Install Jupyter, iPython Notebook, drawing with Matplotlib, and publishing it to Github
iPython and Jupyter Notebook with Embedded D3.js
Downloading YouTube videos using youtube-dl embedded with Python
Machine Learning : scikit-learn ...
Django 1.6/1.8 Web Framework ...
Ph.D. / Golden Gate Ave, San Francisco / Seoul National Univ / Carnegie Mellon / UC Berkeley / DevOps / Deep Learning / Visualization