I like the Python list comprehension syntax.
Can it be used to create dictionaries too? For example, by iterating over pairs of keys and values:
mydi
This code will create dictionary using list comprehension for multiple lists with different values that can be used for pd.DataFrame()
#Multiple lists
model=['A', 'B', 'C', 'D']
launched=[1983,1984,1984,1984]
discontinued=[1986, 1985, 1984, 1986]
#Dictionary with list comprehension
keys=['model','launched','discontinued']
vals=[model, launched,discontinued]
data = {key:vals[n] for n, key in enumerate(keys)}
enumerate
will pass n
to vals
to match each key
with its list
You can create a new dict for each pair and merge it with the previous dict:
reduce(lambda p, q: {**p, **{q[0]: q[1]}}, bla bla bla, {})
Obviously this approaches requires reduce
from functools
.
Just to throw in another example. Imagine you have the following list:
nums = [4,2,2,1,3]
and you want to turn it into a dict where the key is the index and value is the element in the list. You can do so with the following line of code:
{index:nums[index] for index in range(0,len(nums))}
{key: value for (key, value) in iterable}
Note: this is for Python 3.x (and 2.7 upwards). Formerly in Python 2.6 and earlier, the dict
built-in could receive an iterable of key/value pairs, so you can pass it a list comprehension or generator expression. For example:
dict((key, func(key)) for key in keys)
In simple cases you don't need a comprehension at all...
dict
built-in directly:1) consumed from any iterable yielding pairs of keys/vals
dict(pairs)
2) "zip'ped" from two separate iterables of keys/vals
dict(zip(list_of_keys, list_of_values))
Yes, it's possible. In python, Comprehension can be used in List, Set, Dictionary, etc. You can write it this way
mydict = {k:v for (k,v) in blah}
Another detailed example of Dictionary Comprehension with the Conditional Statement and Loop:
parents = [father, mother]
parents = {parent:1 - P["mutation"] if parent in two_genes else 0.5 if parent in one_gene else P["mutation"] for parent in parents}
In Python 3 and Python 2.7+, dictionary comprehensions look like the below:
d = {k:v for k, v in iterable}
For Python 2.6 or earlier, see fortran's answer.