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
{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))