Is it possible to create a dictionary "template"?

I am creating a recipe selector and I want to create a unified dictionary template. I currently have something like this:

menu_item_var = {'name': "Menu Item", 'ing': (ingredients)} 

I am worried about re-typing name and ing for each menu_item_var in time and the likely disaster of the wrong key. I know that I could add the Menu Item as an element 0 to my tuple, erase the dict and run the for loop to make the dictionaries safer, but this will not convert the original menu_item_var from tuple to dict . Is there a smarter way to do this?

+6
source share
5 answers

I would suggest that you need to look for class creation and use 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” is becoming more complex, it becomes more than just defining data and requires logic. Using a class will allow you to encapsulate this.

For example, over our sandwich there are 2 breads and 2 oils. We could track this internally, for example:

 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) 

What gives us:

 sandwich: 2 x butter 1 x cheese 1 x ham 2 x bread 
+5
source

Dictionaries are key-value mappings commonly used to create a flexible structure. Class instances are objects with many properties that are commonly used when you have multiple objects, all of which have a similar structure.

Your “dictionary template” is really more like a class (and all your dictionaries that must match this single template will be instances of the class), since you want these dictionaries not to be collections of an unknown key set, but also contain a certain standard set of values under famous names.

collections.namedtuple is an extremely easy way to build and use just such a class (one instance of which is only objects with a specific 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 "drawback" is that they are still tuples, and therefore immutable. In my experience, this is usually good for small simple objects with regular data, but this may be a disadvantage of the use you have in mind.

+2
source

There are some very simple ways to do this. The easiest way I can think of is to simply create a function to return this vocabulary object.

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

Just call it like that ...

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

EDIT: Edited to use a consistent code style for each PEP8.

+1
source

Alternatively suggested therearetwoosingoose ,

 >>> menu_item = lambda name, ing: {'name': name, 'ing': ing} >>> sandwich = menu_item('sandwich', ['cheese', 'tomato']) 

Now a sandwich:

 >>> sandwich {'name': 'sandwich', 'ing': ['cheese', 'tomato']} 
+1
source

You can try and use json and string interpolation to create a very simple 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'} 
+1
source

Source: https://habr.com/ru/post/957001/


All Articles