Archive

Archive for March, 2012

Three ways of creating dictionaries in Python

March 30, 2012 19 comments

Dictionaries are the fundamental data structure in Python, and a key tool in any Python programmer’s arsenal. They allow O(1) lookup speed, and have been heavily optimized for memory overhead and lookup speed efficiency.

Today I”m going to show you three ways of constructing a Python dictionary, as well as some additional tips and tricks.

Dictionary literals

Perhaps the most commonly used way of constructing a python dictionary is with curly bracket syntax:

d = {"age":25}

As dictionaries are mutable, you need not know all the entries in advance:

# Empty dict
d = {}
# Fill in the entries one by one
d["age"] = 25

From a list of tuples

You can also construct a dictionary from a list (or any iterable) of key, value pairs. For instance:

d = dict([("age", 25)])

This is perhaps most useful in the context of a list comprehension:

class Person(object):
    def __init__(self, name, profession):
        self.name = name
        self.profession = profession

people = [Person("Nick", "Programmer"), Person("Alice","Engineer")]
professions = dict([ (p.name, p.profession) for p in people ])
>>> print professions
{"Nick": "Programmer", "Alice": "Engineer"}

This is equivalent, though a bit shorter, to the following:

people = [Person("Nick", "Programmer"), Person("Alice","Engineer")]
professions = {}
for p in people:
    professions[p.name] = p.profession

This form of creating a dictionary is good for when you have a dynamic rather than static list of elements.

From two parallel lists

This method of constructing a dictionary is intimately related to the prior example. Say you have two lists of elements, perhaps pulled from a database table:

# Static lists for purpose of illustration
names = ["Nick", "Alice", "Kitty"]
professions = ["Programmer", "Engineer", "Art Therapist"]

If you wished to create a dictionary from name to profession, you could do the following:

professions_dict = {}
for i in range(len(names)):
    professions_dict[names[i]] = professions[i]

This is not ideal, however, as it involves an explicit iterator, and is starting to look like Java. The more Pythonic way to handle this case would be to use the zip method, which combines two iterables:

print zip(range(5), ["a","b","c","d","e"])
[(0, "a"), (1, "b"), (2, "c"), (3, "d"), (4, "e")]

names_and_professions = zip(names, professions)
print names_and_professions
[("Nick", "Programmer"), ("Alice", "Engineer"), ("Kitty", "Art Therapist")]

for name, profession in names_and_professions:
    professions_dict[name] = profession

As you can see, this is extremely similar to the previous section. You can dispense the iteration, and instead use the dict method:

professions_dict = dict(names_and_professions)
# You can dispence the extra variable and create an anonymous
# zipped list:
professions_dict = dict(zip(names, professions))

Further reading

zip

dict

Categories: Python Tags: , , ,

Bashmarks – bookmarks for terminal navigation

March 23, 2012 Leave a comment

Bashmarks is an invaluable script by Huy Nguyen which allows you to easily navigate to specific directories via the command line. Borrowing the usage section from The usage section from his website should illustrate its utility nicely:

$ cd /var/www/
$ s webfolder
$ cd /usr/local/lib/
$ s locallib
$ l
$ g web<tab>
$ g webfolder

I have half a dozen or so directories in which I need to get to quickly, so I have created a bashmark for each of them. This allows me to type g <1 or 2 letters><tab><enter> to get to the directory, rather than having to tab complete a whole slew of folders. Over the course of the day, this saves dozens of keystrokes, and generally contributes to the sense of flow when trying to accomplish a task. Combine this with liberal use of cd - (jump to previous location), and you can navigate between arbitrary locations extremely easily.

I highly recommend this script if you do any sort of work in a terminal.

Categories: Uncategorized

An interview with William Wilson, self-taught developer of Fret Tester and more

March 13, 2012 2 comments

I recently had the opportunity to speak with William Wilson, the man behind Fret Tester, the best guitar fretboard learning application available for iOS, and one of the nicest designed apps I’ve used. I wrote about its great UI features in my previous post, The Best iPhone Guitar Fretboard App: Usability Lessons Learned. I wanted to pick the designer’s brain to see what lessons he could impart about designing usable applications. Here’s what he had to say.


Please tell me a little about your background. Do you design mobile applications for a living or as a hobby?

Guitar Hero Pullquote

I’m actually a professional guitarist. I make my living teaching and performing classical and Spanish guitar in San Diego. I’ve always loved programming, starting with Basic, then HyperCard, Java, Flash, and eventually C. I started designing apps for my guitar students as a way to compete with Guitar Hero. I got tired of hearing: “Sorry Mr. Wilson, I didn’t practice, but I played Guitar Hero, does that count?” My first attempts were in Java, and were really awful. I’ve since done about 15 flash games (on my site guitargames.net) and 4 iOS apps. I’ve mostly learned from books and online tutorials. Right now it’s a hobby, but I’d love to do more of it.


As a musician first and foremost, what were the deficiencies you saw in the other published guitar apps and how did you aim to address them?

Traditionally when learning the neck students start with the natural (not sharp and flat) notes. That way they establish landmarks on the neck. I didn’t see this feature being a big part of any app. For me having the iPhone version just display the natural notes made sense (with a button to shift into sharps). Plus it’s tough to fit 12 buttons on the screen without clutter.

One of the biggest challenges I saw was how to zoom in on the neck. With many of the apps, I tried I lost a sense of where I was on the neck. But if the whole neck was shown it was too small. I decided to have my app zoom to the area that was being tested, but to allow sufficient area on either side so the user had a sense for where they were. Plus I included the option to zoom all the way out should the user prefer it. Related to this, I thought many of the apps lacked reinforcement. When you pushed the correct answer your finger covered it. I added the key style buttons so users could see what note the pushed and thus reinforce the correct answer.

Fret Tester screenshot

Fret Tester screenshot - note that only the natural keys are shown and that the incorrect answer that was pressed pops up above the obstructing finger


How have your students received your work? Have you seen a measurable improvement in their progress?

I wish I could say that the app was a runaway success with my students… Unfortunately there is a mindset out there that you aren’t practicing unless you have a guitar in your hand. Mental practice is too often neglected, both with note naming and music theory. For the students who have taken my advice and used the app I’ve seen good things. I think separating the mental and physical complexities of the guitar is the way to go.


What advice would you offer to other people who are not programmers by trade but have an idea for a program or application that could simplify or improve some aspect of their everyday life? What resources have you found that were useful in turning your dream into reality?

There are tons of great resources out there. I always recommend http://masters-of-the-void.com/ as a first step. Also Steven Kochan’s Programming in Objective C is great for learning to write for iOS.

Obvious pullquote

Outside “traditional” programming there were three books that greatly influenced me. One is The Non-Designer’s Design Book by Robin Williams, it will help you design a decent looking app. Second is Dave Woolridge’s Business of iPhone App Development, make sure you can sell one or two before you spend a year creating an app. And finally Don’t Make Me Think by Steve Krug, a guide for good UI principles.

Also I would say make sure to beta test often. I had about 8 people test Fret Tester and learned something from everyone. I like to hand someone my phone and say, try this. You’d be amazed at how they struggle to find something you thought was obvious.


You mentioned making sure that you can sell a product before you invest too much time in producing it. How do you recommend that app developers do this? Do you create a bare bones v 0.0 prototype and put it on the app store to gauge interest? Or do you have an alternative technique for market research?

Wife nuts pullquote

First I look around and see if there are similar apps already out there. If there are a ton, and they’re good, I move on. If there are none I also move on, since there probably isn’t a market for what I’m designing, I want to at least see things that are similar. My goal is to design an app that reaches an already existing need. Not that I’m always successful in it. After reading Woolridge’s book, as well as listening to Seth Godin’s Purple Cow (Audio Book) I’ve improved in this area. I also just talk to people about my idea. If my wife looks at me like I’m nuts (which happens frequently) I try to rethink things.


Are you working on any new projects currently? Or do you have ideas for the next thing you want to work on?

Yes, I’ve been playing around with Adobe’s new Stage 3D and the Starling Framework. It seems promising. I’m hoping to release my first game using it soon. It is called Tab Warrior and is kind of a cross between Fret Tester and Space Invaders. Also, I’m going to try my hand at an Android app this year.


Great to hear. Thank you for taking the time to speak with me. Do you have any parting thoughts for the readers?

80% pullquote

One thing I read in Apple’s docs was to only include features in an app that 80% of users will use. That totally changed my approach. If you look at Apple’s success I think its largely the result of keeping things simple and easy to use, and gearing products for the average user. Take the same approach in your apps.


Thank you to Mr. William Wilson for granting me this interview. You can find more about him on his website, WilliamWilson.com. See my Google+ album for more screenshots of Fret Tester.

Closing a subset of tabs in Google Chrome

March 5, 2012 Leave a comment

Do you use Google Chrome? Do you sometimes want to close multiple tabs at once? Here are three ways to do that, two of which are not immediately obvious.

Close Tabs to the Right

This is the standard way I’ve been using to close tabs. You right click on a tab, choose “Close Tabs to the Right”, and all tabs to the right of that tab are closed. This works well for two reasons:

  1. When you manually create a new tab, it opens on the far right
  2. When you open links in a new tab, it will open immediately to the right of the tab you’re currently in.

Thus if you have opened a few tangentially related tabs from a main article, you can click on the main article’s tabs, choose Close Tabs to the Right, and all of those newly opened tabs will go away.

Ctrl/Meta click tabs

You can add tabs to the current selection by holding control (Windows/Linux) or command (OSX) while clicking on additional tabs. This is exactly the same behavior as when you are selecting multiple files from the desktop GUI. Once you have the tabs you want to close selected, you can right click on any one of the selected tabs and choose “Close Tabs.” This approach works better than the “Close Tabs to the Right” approach when the tabs you want to close are not all next to each other.

Control click example

Why might you want to do this rather than clicking the X in each tab individually? I can think of two main reasons.

The first is that it provides you with a much larger click target for each tab. With this method, you can click almost the entire tab to add it to the selection, then right click almost the entire area of any of these tabs to bring up the context menu to close tabs. The X button itself, by contrast, has a small clickable area that requires more dexterity. (See the Wikipedia article on Fitt’s Law for more information on the relationship between accurate navigation to a UI element and the size of that UI element)

The second reason you might use this method is that it allows you to make your selections all at once before closing any one of them. If you close them one at a time, the tabs move around to take up the empty space. The Chrome team has done an amazing team with the UI design of the standard close tab functionality (e.g. the close button will always stay under your mouse cursor as the tabs reshuffle, and they only will change size once your cursor leaves the tab bar), but it might still be more intuitive to select them all at once while their location is fixed rather than finding them in the changing tab bar as each consecutive tab is closed.

See this excellent blog post by Basil Safwat for more on the Chrome tab close behavior.

Shift click tabs

Finally, you can extend the selection of tabs by shift clicking on any other tab. In other words, the currently opened tab is one endpoint of the selection, you shift click on any other tab (either to the left or right), and that becomes the other endpoint in the selection interval. Here is an illustration of the process:

Shift click example

Once you have your selection, you can right click on any of them and choose Close Tabs as mentioned earlier. This approach is best when you have a contiguous span of tabs you want to close, but there are some tabs to the right that you want to keep open.

Conclusion

I hope you found this brief foray into the ways of closing multiple tabs in Chrome as interesting. I think most Chrome users know of the Close Tabs to the Right option, but I would guess most people don’t know about about the shift click and ctrl/command click ways of selecting tabs.

Categories: Uncategorized Tags: , , , ,