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.
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.
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
This recipe has been accepted into Python 2.3. > Your suggested code is Ok. But you shouldn't call
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 :-).
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:
Inline quote minimization.