Python str.format() list of dictionaries
<p>I am trying to develop a format that prints a certain way when iterating through a list of dictionaries. </p>

<p>Error Raised: "tuple index out of range"</p>

<p>I have looked at several other questions that with a similar topic and know that you can't key in using a numerical value and format(). At least that's what I got from it. </p>

<p>In my case I am not using a numerical value so not sure why it isn't working. I think I know how to solve this using the other (%S) formatting method but trying to condense and make my code more pythonic. </p>

<p>So when I remove the .formate statement and leave the indexing arguments I get the correct values, but as soon as I try to format them I get the error. </p>

<p>My code:</p>

<pre><code>def namelist(names):
    n = len(names)
    return_format = {
    0: '{}',
    1: '{} &amp; {}',
    2:'{}, {} &amp; {}'
    }
    name_stucture = return_format[n-1]
    for idx, element in enumerate(names):
        print name_stucture.format(names[idx]["name"])
</code></pre>

<p>Looking for why this is happening and how to resolve it, thanks!</p>

<p>The error you are getting occurs when you try to unpack a format string with too few arguments. Here is a basic example:</p>

<pre><code>&gt;&gt;&gt; '{}{}'.format('test')
Traceback (most recent call last):
  File "&lt;stdin&gt;", line 1, in &lt;module&gt;
IndexError: tuple index out of range
</code></pre>

<p>This occurs even if you pass a list as one argument. You need to <em>unpack</em> the list with the asterisk:</p>

<p>Without unpacking:</p>

<pre><code>&gt;&gt;&gt; x = ['one', 'two']
&gt;&gt;&gt; '{}{}'.format(x)
Traceback (most recent call last):
  File "&lt;stdin&gt;", line 1, in &lt;module&gt;
IndexError: tuple index out of range
</code></pre>

<p>With unpacking:</p>

<pre><code>&gt;&gt;&gt; x = ['one', 'two']
&gt;&gt;&gt; '{}{}'.format(*x)
'onetwo'
</code></pre>

<h2>Edit</h2>

<p>There are some other issues as well: you are looping through each name and printing the specified format, but there is no need for looping at all unless you want to print the names three times each. The use of <code>names[idx]</code>, instead of just <code>element</code> is also unnecessary and unpythonic.</p>

<p>Preserving some of your patterns, here is a working example:</p>

<pre><code>names = [ {'name': 'George'}, {'name': 'Alfred'}, {'name': 'Abe'}]

def namelist(names):
  name_structure = ['{}', '{} &amp; {}', '{}, {}, &amp; {}'][min(2, len(names) - 1)]
  name_structure.format(*[name['name'] for name in names])
</code></pre>

<p>Note that this function will have unexpected behavior if you have more than three names: it will only print the first three names.</p>

python list dictionary format