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 (2016, retired 2019) Dictionaries Packing and Unpacking Dictionaries

Noah Fields
Noah Fields
13,985 Points

Program not Working, Troubleshooting Help?

Currently, my program is as follows:

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

def string_factory(dict_list):
    new_list = []
    for diction in dict_list:
        unpacked = (**diction)
        if name and food in unpacked:
            string = ("Hi, I'm {} and I love to eat {}!".format(name, food))
            new_list.append(string)

Unpacked is based on code from this page: http://python-reference.readthedocs.io/en/latest/docs/operators/dict_unpack.html

I found this while looking for ways to unpack a dictionary based on a variable name (diction in this case), because I cannot reference it directly without knowing what arguments the user will pass to it.

When running this code, I am told there is a syntax error on line 11. I copied this code into IDLE, which highlights syntax errors, and the highlighted portion was the second asterisk on the line:

unpacked = (**diction)

Most critically, I need to know the proper way to unpack each dict in the list, without exactly specifying each dict. The video used one created on the spot, rather than one that was then referenced by a variable. As such, I'm not sure how to solve this problem.

The reason I believe you have the syntax error is because unpacking is only done inside a function call

I was able to get the output by changing a few things on your code

  1. name and food in the IF statement should be in quotes to avoid NameError
  2. The dictionaries in the dict_list can directly be used in the IF statement
  3. Unpacking of 'diction' happens inside the .format() call

def string_factory(dict_list): new_list = [] #print new_list for diction in dict_list: #unpacked=(diction) if "name" and "food" in diction: string = ("Hi, I'm {name} and I love to eat {food}!".format(diction)) new_list.append(string) #print new_list return new_list

Regards, -Lionel