Thursday, April 19, 2012

Python string interpolation "fill in the blanks"

Here are some examples of "fill in the blanks" string formatting in Python. There are a thousand ways to skin this snake, and all of them work.

The examples shown all lead to the same result, errors are explained where appropriate:


>>> str1 = 'My favorite meal is %s and %s'
>>> str2 = 'My favorite meal is %(one)s and %(two)s'
>>> a = ('spam', 'more spam')    # note a is a tuple
>>> b = ['spam', 'more spam']    # note b is a list
>>> c1 = "one, two"
>>> c2 = "spam, more spam"
>>> d = {'one': 'spam', 'two': 'more spam'}   # note d is a dict
>>> e = dict(one = 'spam', two = 'more spam')  
>>> e
{'two': 'more spam', 'one': 'spam'}
>>> zip(c1.split(", "), c2.split(", "))
[('one', 'spam'), ('two', 'more spam')]
>>> f = dict(zip(c1.split(", "), c2.split(", ")))
>>> f
{'two': 'more spam', 'one': 'spam'}
>>> str1 % a
'My favorite meal is spam and more spam'
>>> str1 % b        # this doesn't work because b is only one argument
Traceback (most recent call last):  
  File "<stdin>", line 1, in <module> 
TypeError: not enough arguments for format string
>>> str1 % tuple(b)      # but this does, after making be a tuple
'My favorite meal is spam and more spam'
>>> str2 % d
'My favorite meal is spam and more spam'
>>> str2 % e
'My favorite meal is spam and more spam'
>>> str2 % f
'My favorite meal is spam and more spam'
>>> g = [('one', 'spam'), ('two', 'more spam')]
>>> h = {k:v for k,v in g}
>>> h
{'two': 'more spam', 'one': 'spam'}
>>> str2 % h
'My favorite meal is spam and more spam'
>>> i = dict((k,v) for k,v in g)
>>> i
{'two': 'more spam', 'one': 'spam'}
>>> str2 % i
'My favorite meal is spam and more spam'
>>> 

happy coding!

Sunday, July 24, 2011

Playing with javascript creation of multi-level associative arrays, starting with flat associative arrays.

I am working with JSON data in the form of a list of associative arrays. The data comes from a web service, and I can't change the form it comes in. 
The JSON data from the web service looks like this:
   [    
    {flavor: "Spam", price: "low", rating: "good"},
    {flavor: "Ham", price: "medium", rating: "waste"},
    {flavor: "Eggs", price: "medium", rating: "better"},
    {flavor: "SpamAndEggs", price: "high", rating: "want"}    
]

I want to parse and rework it into an array of arrays, indexed by the 'flavor', so I can access the data in the form of Spam.price, Eggs.rating, etc.
To do this, I will create new objects like this client side, using javascript. I want my new objects to look like this:

{ 
  'Spam: {flavor: "Spam", price: "low", rating: "good"},  
  'Ham: {flavor: "Ham", price: "medium", rating: "waste"},    
   ..... etc.  
}


After playing around a bit I came up with an answer, putting it here so I can find it later. Maybe it will help you.
First, define a variable from the JSON data:

var food = [ 
  {flavor: "Spam", price: "low", rating: "good"}, 
  {flavor: "Ham", price: "medium", rating: "waste"}, 
  {flavor: "Eggs", price: "medium", rating: "better"}, 
  {flavor: "SpamAndEggs", price: "high", rating: "want"} 
]


Next, define a function to re-work the data into a new dictionary:

new_dict = {}; 
var cook = function (food) {
for (x in food) {
  var foodIndex= food[x]['flavor'];
  new_dict[foodIndex] = food[x];
  };
};
cook(food);


Putting it all together, you can test it by saving this as an html page or use a w3schools 'try it' editor:
<html>
  <head>
    <script type="text/javascript">
      var food = [ 
        {flavor: "Spam", price: "low", rating: "good"}, 
        {flavor: "Ham", price: "medium", rating: "waste"},     
        {flavor: "Eggs", price: "medium", rating: "better"}, 
        {flavor: "SpamAndEggs", price: "high", rating: "want"} 
        ]
      new_dict = {}; 
      var cook = function (food) {
        for (x in food) {
          var foodIndex= food[x]['flavor'];
          new_dict[foodIndex] = food[x];
          };
        };
      cook(food);
    </script>
  </head>
  <body>
    <script type="text/javascript">
       document.write(JSON.stringify(new_dict));
       document.write("<br /><br />");
       document.write(new_dict["Spam"]["flavor"]);
       document.write("<br />");
       document.write(new_dict.Ham.flavor);
       document.write("<br />");
       document.write(new_dict["Eggs"].flavor);
       document.write("<br />");
       document.write(new_dict.SpamAndEggs["flavor"]);
    </script>
  </body>
</html> 


The resulting output should look like this:


{"Spam":{"flavor":"Spam","price":"low","rating":"good"},"Ham":{"flavor":"Ham","price":"medium","rating":"waste"},"Eggs":{"flavor":"Eggs","price":"medium","rating":"better"},"SpamAndEggs":{"flavor":"SpamAndEggs","price":"high","rating":"want"}}

Spam
Ham
Eggs
SpamAndEggs

Sunday, July 17, 2011

My path to learning Python, Django, mySQL, jQuery, HTML, CSS, and the like.

This is a repository of tips and snags that I've encountered and solved (at least functionally) while website development.

Of some use perhaps to others, it's primary purpose is to serve my own needs as an electronic memory.

For use when I later run into an error and think to myself "Hey, I've seen this before.... I wonder how I solved this problem last time?"