Mapping a list as dictionary values
<p>I have a list of strings called lst which contains name, city, and email addresses for three people in such order. I have a dictionary called data that only contains keys.</p>

<pre><code>lst = ['James','New York','james@email.com','Matt','San Francisco','matt@email.com','Jessica','Los Angeles','jessica@email.com']

data = {
            "Name": None,
            "City": None,
            "email": None
        }
</code></pre>

<p>I would like to map lst items as values in data and produce a new list of dictionaries as below,</p>

<pre><code>newlst = [{
            "Name": "James",
            "City": "New York",
            "email": "james@email.com"
        },
        {
            "Name": "Matt",
            "City": "San Francisco",
            "email": "matt@email.com"
        },
        {
            "Name": "Jessica",
            "City": "Los Angeles",
            "email": "jessica@email.com"
        }]
</code></pre>

<p>I know how to add a single value to a specific key in a dictionary like data["Name"] = "James" but how would I achieve this by using list/dict comprehension or iteration?</p>

<p>Here it is.</p>

<pre><code>lst = ['James','New York','james@email.com','Matt','San Francisco','matt@email.com','Jessica','Los Angeles','jessica@email.com']
newlst = []

for i in xrange( 0, len(lst), 3 ):
    d = {}
    d['Name'] = lst[i]
    d['City'] = lst[i+1]
    d['Email'] = lst[i+2]

    newlst.append( d )

print newlst
</code></pre>

<p>Output:</p>

<pre><code>[{'City': 'New York', 'Email': 'james@email.com', 'Name': 'James'},
 {'City': 'San Francisco', 'Email': 'matt@email.com', 'Name': 'Matt'},
 {'City': 'Los Angeles', 'Email': 'jessica@email.com', 'Name': 'Jessica'}]
</code></pre>

<p>Using comprehension:</p>

<pre><code>lst = ['James','New York','james@email.com','Matt','San Francisco','matt@email.com','Jessica','Los Angeles','jessica@email.com']
newlst = [{'Name':lst[i], 'City':lst[i+1], 'Email':lst[i+2]} for i in xrange(0,len(lst),3)]
</code></pre>

python list dictionary list-comprehension