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 problem seems simpler than you're trying to make it:</p>

<pre><code>formats = [None, '{}', '{} &amp; {}']

def namelist(names):
    length = len(names)

    if length &gt; 2:
        name_format = '{}, ' * (length - 2) + formats[2]  # handle any number of names
    else:
        name_format = formats[length]

    print(name_format.format(*names))

namelist(['Tom'])
namelist(['Tom', 'Dick'])
namelist(['Tom', 'Dick', 'Harry'])
namelist(['Groucho', 'Chico', 'Harpo', 'Zeppo'])

# the data structure is messy so clean it up rather than dirty the function:
namelist([d['name'] for d in [{'name': 'George'}, {'name': 'Alfred'}, {'name': 'Abe'}]])
</code></pre>

<p><strong>OUTPUT</strong></p>

<pre><code>&gt; python3 test.py
Tom
Tom &amp; Dick
Tom, Dick &amp; Harry
Groucho, Chico, Harpo &amp; Zeppo
George, Alfred &amp; Abe
&gt; 
</code></pre>

python list dictionary format