Is it possible to create a dictionary "template"?

You could try and use json and string interpolation to create a very basic dict template:

import json
template = '{"name": "Menu Item", "ing": %s }'

def render(value):
    return json.loads(template % json.dumps(value))

render([1,2,3])
>> {u'ing': [1, 2, 3], u'name': u'Menu Item'}

Dictionaries are key-value mappings, generally used to have a flexible structure. Class instances are objects with a bunch of properties, generally used when you have a number of objects that all have a similar structure.

Your "dictionary template" really sounds more like a class (and all your dictionaries that need to fit this single template would be instances of the class), since you want these dictionaries not to be collections of an unknown set of key-value pairs, but to contain a particular standard set of values under known names.

collections.namedtuple is an extremely lightweight way of constructing and using exactly this kind of class (one whose instances are just objects with a particular set of fields). Example:

>>> from collections import namedtuple
>>> MenuItem = namedtuple('MenuItem', ['name', 'ing'])
>>> thing = MenuItem("Pesto", ["Basil", "Olive oil", "Pine nuts", "Garlic"])
>>> print thing
MenuItem(name='Pesto', ing=['Basil', 'Olive oil', 'Pine nuts', 'Garlic'])
>>> thing.name
'Pesto'
>>> thing.ing
['Basil', 'Olive oil', 'Pine nuts', 'Garlic']

The "downside" is that they're still tuples, and so immutable. In my experience that's usually a good thing for small simple plain-data objects, but that might be a drawback for the usage you have in mind.


There are several very simple ways of doing this. The simplest way that I can think of would be to just create a function to return that dictionary object.

def get_menu_item(item, ingredients):
    return {'name': item, 'ing': ingredients}

Just call it like this...

menu_item_var = get_menu_item("Menu Item", (ingredients))

EDIT: Edited to use consistent code styling, per PEP8.


I'd probably suggest looking at creating a class and using OOP instead for something like this.

class Recipe:
    def __init__(self,name,ingredients):
        self.name = name
        self.ingredients = ingredients
    def __str__(self):
        return "{name}: {ingredients}".format(name=self.name,ingredients=self.ingredients)

toast = Recipe("toast",("bread"))
sandwich = Recipe("sandwich",("bread","butter","ham","cheese","butter","bread"))

As your "template" get more and more complex, it becomes more than just a data definition and requires logic. Using a Class will allow you to encapsulate this.

For example, above our sandwich has 2 breads and 2 butters. We might want to keep track of this internally, like so:

class Recipe:
    def __init__(self,name,ingredients):
        self.name = name
        self.ingredients = {}
        for i in ingredients:
            self.addIngredient(i)
    def addIngredient(self, ingredient):
        count = self.ingredients.get(ingredient,0)
        self.ingredients[ingredient] = count + 1
    def __str__(self):
        out =  "{name}: \n".format(name=self.name)
        for ingredient in self.ingredients.keys():
            count = self.ingredients[ingredient]
            out += "\t{c} x {i}\n".format(c=count,i=ingredient)
        return out

sandwich = Recipe("sandwich",("bread","butter","ham","cheese","butter","bread"))
print str(sandwich)

Which gives us:

sandwich:
    2 x butter
    1 x cheese
    1 x ham
    2 x bread