Welcome, guest | Sign In | My Account | Store | Cart

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

Python, 12 lines
 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)

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.

3 comments

Kent Johnson 17 years, 8 months ago  # | flag

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
Andrew Dalke 17 years, 8 months ago  # | flag

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}
>>>
Leonardo Santagada 17 years, 8 months ago  # | flag

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

Created by runsun pan on Tue, 1 Aug 2006 (PSF)
Python recipes (4591)
runsun pan's recipes (5)

Required Modules

  • (none specified)

Other Information and Tasks