Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python Python Collections (Retired) Dictionaries String Formatting with Dictionaries

Formatting strings with dicts -

So after reading Chris's Forum Solution to another persons (long script) I was able to come to this code as a correct solution. However, I still don't totally get why it worked.

Will this " **iterable_dict " stuff become more clear as I continue or am I missing the boat?

Thanks!

strings.py
dicts = [
    {'name': 'Michelangelo',
     'food': 'PIZZA'},
    {'name': 'Garfield',
     'food': 'lasanga'},
    {'name': 'Walter',
     'food': 'pancakes'},
    {'name': 'Galactus',
     'food': 'worlds'}
]

string = "Hi, I'm {name} and I love to eat {food}!"


def string_factory(dicts, string):
  new_list = []
  for itble_dict in dicts:
    new_string = string.format(**itble_dict)
    new_list.append(new_string)
  return new_list

1 Answer

Chris Freeman
MOD
Chris Freeman
Treehouse Moderator 68,423 Points

The double-asterisks can be used as a parameter to receive an arbitrary number of keyword arguments and store in a dict.

Given a function:

def func(**args):
    pass

was called with (name='Michelangelo', food='PIZZA') then within func, args would be equivalent to

{'name': 'Michelangelo', 'food': 'PIZZA'}

It can also be used, with a dict, as an argument to "unpack" the dictionary into an equivalent keyword arguments.

if iterable_dict is {'name': 'Michelangelo', 'food': 'PIZZA'} then **iterable_dict would expand to:

name='Michelangelo', food='PIZZA'

Post back if this is not clear.