Skip to content

Instantly share code, notes, and snippets.

@danlkv
Last active June 4, 2020 05:02
Show Gist options
  • Save danlkv/abb9956b173a33f94327f03fbd4d0eff to your computer and use it in GitHub Desktop.
Save danlkv/abb9956b173a33f94327f03fbd4d0eff to your computer and use it in GitHub Desktop.

Interpolate dict

Intro

Let's say you have a text string that greets a person, 'Hello, Mark!'. If you write a program for this greeting you might want to compose the string for any name of the person. One way to do this is to have a template string, 'Hello, ${user_name}!' and then use a function that will replace the ${...} with value of variable user_name. This is usually called string interpolation.

We want to have a dict interpolation, where the same is done for a nested structure. For example, if you have a dictionary, {'user':'User_id${uid}'}, and a variable uid=1, we want to get dictionary {'user':'User_id1'}.

Template strings

This is already built into python for strings.

https://docs.python.org/3/library/string.html#template-strings

>>> from string import Template
>>> s = Template('$who likes $what')
>>> s.substitute(who='tim', what='kung pao')
'tim likes kung pao'

Other libraries to check out

Definitions

  • Template - string(dict?) that specifies the structure of resulting object.
  • Variables - variables to put into Template

Task

Suppose that you have a Template provided by some user you don't know. He also could be a hacker. You have to write a function that takes

  1. a json-serializable template
  2. dictionary of variables and interpolates them. After that it parses the json and returns dict

You may use any template format language

Criteria

  • Readability
  • Will this code work for lists?
  • What if variable itself is a dict?
template = '{"post":"$post_data"},
variables = {'post_data':{"text":"hello","user":"Mark"}}
  • What if variable itself has a JSON object?
template = '{"post":"$post_data"},
variables = {'post_data':'{"text":"hello","user":"Mark"}'}
  • What if our Template is dict, not string?

Advices

  1. First read the docs and other solutions
  2. Think before writing
  3. After you think you understand how to do, describe it and send the description to me.
  4. If you have any, even the most stupid in the world question - ask me.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment