ActiveState Code

Recipe 496926: Dictionary tool for lazy typers


This recipe provides an alternative way of generating and updating dictionaries. It savs couple of keystrokes, making routine dict operations easier.

Python
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
# new dictionary. Instead of {"a":3}, do this: nd(a=3)

def nd(**kargs): 
    d={}
    d.update(kargs)
    return d

# update dict. Instead of d.update({"a":3,"b":4}),
# do this: ud(d,a=3,b=4) 

def ud(obj, **kargs): 
    obj.update(kargs)

Discussion

I've been spending some time on javascript lately. Javascript's dictionary (although it's not called by that name) defers from python's by allowing dict key been entered as literal strings. For example,

{age:5}

is legal for js, but not legal for py. In py you have to do:

{"age":5}

As a lazy typer myself, I imagine how many key strokes I can avoid by having the same feature in python. This recipe provides a mechinasm for doing so.

So, instead of

d= {"a":3} d.update({"b":4})

we can do this:

d = nd(a=3) ud(d, b=4)

It might not make any sense at the first glance, but consider situations when the size of the dict is large. For example, if you see

john = {"age":10, "height":180, "weight":150, "eyeColor":"black", ...} john.update({"favBook":"none","favMovie":"none", ...})

vs

john = nd(age=10, height=180, weight=150, eyeColor="black", ...) ud(john, favBook="none", favMovie="none", ...)

you might start to appreciate it.

Besides making it shorter, it actually makes it cleaner.

Certainly, this is not the 'one-size-fits-all' solution. In some conditions this approach will break. Since it's easy to spot them, I'll leave that to the readers.

Comments

  1. 1. At 4:24 p.m. on 1 aug 2006, Kent Johnson said:

    dict(a=3) works since Python 2.3. You can supply keyword arguments to dict() since Python 2.3. If 'dict' is too long then you can alias it with

    nd = dict
    
  2. 2. At 11:55 a.m. on 2 aug 2006, Andrew Dalke said:

    dict update also takes kwargs.

    >>> d = dict(a=3)
    >>> d.update(b=4)
    >>> d
    {'a': 3, 'b': 4}
    >>> john = dict(age=10, height=180, weight=150, eyeColor="black")
    >>> john.update(favBook="none", favMovie="none")
    >>> john
    {'eyeColor': 'black', 'favMovie': 'none', 'weight': 150, 'favBook': 'none', 'age': 10, 'height': 180}
    >>>
    
  3. 3. At 9:49 p.m. on 3 aug 2006, Leonardo Santagada said:

    runsun pan don't be mad, sometimes I also reinvent a unknow wheel :)

Sign in to comment