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

The syntax for constructing a dictionary can be tedious due to the amount of quoting required. This recipe presents a technique which avoids having to quote the keys.

Python, 7 lines
1
2
3
4
5
6
7
# the standard way
data = { 'red' : 1, 'green' : 2, 'blue' : 3 }

# a cleaner way
def dict(**kwargs): return kwargs

data = dict(red=1, green=2, blue=3)

I've often found myself missing Perl's "=>" operator which is well suited to building hashes (perl-speak for dictionaries) from a literal list:

%data = (red => 1, green => 2, blue => 3);

The "=>" operator in Perl is equivalent to "," except that it implicitly quotes the word to the left.

I noticed that Perl's syntax is very similar to Python's function-calling syntax for passing keyword arguments. And the fact that Python collects the keyword arguments into a dictionary turned on a light bulb in my head.

This approach should be very efficient since the compiler is doing equivalent work as with the dictionary literal. It is admittedly idiomatic, but it can make large dictionary literals a lot cleaner and a lot less painful to type.

4 comments

Peter Abel 20 years, 9 months ago  # | flag

Method for constructing a dictionary without. Your suggested code is Ok. But you shouldn't call a function dict because it's a builtin-function. Regards Peter

Ganesan Rajagopal 20 years, 6 months ago  # | flag

This recipe has been accepted into Python 2.3. > Your suggested code is Ok. But you shouldn't call

a function dict because it's a builtin-function.

dict is not a built-in function. dict is a built-in type since Python 2.2. You can verify this by typing "type(dict)" at the interactive prompt.

If you look at the date of the recipe and you'll realize that this is the exact syntax has been accepted into Python 2.3 :-).

Ganesan Rajagopal 20 years, 6 months ago  # | flag

Avoiding excessive quoting during access. Nice to see this Recipe accepted into Python 2.3. Another thing I miss from Perl is reduced quoting for access. When you access $data{red}, Perl automatically quotes the key for you. In Python you need to do data['red']. Wouldn't it be nice if you didn't have to do the quoting like in Perl? In fact, since you can inherit from types since Python 2.2, we can do one better than Perl. With the following code you can access data['red'] simply as data.red. Code follows:

class attrdict(dict):
    def __getattr__(self, name):
        return self[name]

    def __setattr__(self, name, value):
        self[name] = value

data = attrdict(red=1, green=2, blue=3)
print data.red
data.black = 4
Frank P Mora 18 years, 11 months ago  # | flag

Inline quote minimization.

There are times when inline functionality is desired without defining functions or classes.
Lambda and map served this purpose well but might be leaving Python.
List compressions (a la Haskell)  will fill the void.
In the above examples dictionary values are literal integers.
Sometimes they might be strings requiring quotes.

>>> ls1= "m1 m2 m3 m4 m5 m6 m7 m8 m9 m10 m11 m12"
>>> ls2= "January February March April May June July August September October November December"

>>> dict( zip( *[  l.split() for l in ( ls1, ls2) ] ))

The asterisk (*) before the list compression is necessary for zip to not interpret the nested
result of the compression as a single argument.


To have literal, keyed access to the dictionary values without class or function definitions:

>>> import __main__; MD=__main__.__dict__
>>> MD.update( dict( zip( *[  l.split() for l in ( ls1, ls2) ] )) )

>>> print "Quarters start in the months %s, %s, %s and %s."  %  (m1, m4, m7, m10)

Quarters start in the months January, April, July and October.
Created by Brent Burley on Tue, 27 Mar 2001 (PSF)
Python recipes (4591)
Brent Burley's recipes (7)
Python Cookbook Edition 2 (117)
Python Cookbook Edition 1 (103)

Required Modules

  • (none specified)

Other Information and Tasks