Build Dictionary in Python Loop - List and Dictionary Comprehensions Build Dictionary in Python Loop - List and Dictionary Comprehensions python python

Build Dictionary in Python Loop - List and Dictionary Comprehensions


The short form is as follows (called dict comprehension, as analogy to the list comprehension, set comprehension etc.):

x = { row.SITE_NAME : row.LOOKUP_TABLE for row in cursor }

so in general given some _container with some kind of elements and a function _value which for a given element returns the value that you want to add to this key in the dictionary:

{ _key : _value(_key) for _key in _container }


What you're using is called a list comprehension. They're pretty awesome ;)

They have a cousin called a generator expression that works like a list comprehension but instead of building the list all at once, they generate one item at a time. Hence the name generator. You can even build functions that are generators - there are plenty of questions and sites to cover that info, though.

You can do one of two things:

x = dict(((row.SITE_NAME, row.LOOKUP_TABLE) for row in cursor))

Or, if you have a sufficiently new version of Python, there is something called a dictionary comprehension - which works like a list comprehension, but produces a dictionary instead.

x = {row.SITE_NAME : row.LOOKUP_TABLE for row in cursor}


You can do it like this:

x = dict((row.SITE_NAME, row.LOOKUP_TABLE) for row in cursor)