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's an approach using list comprehension. The idea is that we create a dictionary based on a zip of the keys and three values of a time.</p>

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

keys = [
    'Name',
    'City',
    'email',
]

newlst = [
    dict(zip(keys, values)) for values in [iter(lst)] * len(keys)
]
print(newlst)
</code></pre>

<p><strong>Output</strong>:</p>

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

<p><code>[iter(lst)] * len(keys)</code> will return chunks of 3 values at a time from the list. <code>zip(keys, values)</code> will then produce an iterator of tuples containing a key and corresponding value. Finally, <code>dict()</code> will turn this into a dictionary to be inserted into <code>newlst</code>. This loops until the list is exhausted.</p>

python list dictionary list-comprehension