Skip to Content
Python Cookbook
book

Python Cookbook

by Alex Martelli, David Ascher
July 2002
Intermediate to advanced
608 pages
15h 46m
English
O'Reilly Media, Inc.
Content preview from Python Cookbook

Constructing a Dictionary Without Excessive Quoting

Credit: Brent Burley

Problem

You’d like to construct a dictionary without having to quote the keys.

Solution

Once you get into the swing of Python, you may find yourself constructing a lot of dictionaries. However, the standard way, also known as a dictionary display, is just a smidgeon more cluttered than you might like, due to the need to quote the keys. For example:

data = { 'red' : 1, 'green' : 2, 'blue' : 3 }

When the keys are identifiers, there’s a cleaner way:

def makedict(**kwargs):
    return kwargs
data = makedict(red=1, green=2, blue=3)

You might also choose to forego some simplicity to gain more power. For example:

def dodict(*args, **kwds):
    d = {}
    for k, v in args: d[k] = v
    d.update(kwds)
    return d
tada = dodict(yellow=2, green=4, *data.items())

Discussion

The syntax for constructing a dictionary can be slightly tedious, due to the amount of quoting required. This recipe presents a technique that avoids having to quote the keys, when they are identifiers that you already know at the time you write the code.

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 Perl’s own ,, except that it implicitly quotes the word to its left.

Perl’s syntax is very similar to Python’s function-calling syntax for passing keyword arguments. And the fact that Python collects the ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Modern Python Cookbook - Second Edition

Modern Python Cookbook - Second Edition

Steven F. Lott
Python Cookbook, 3rd Edition

Python Cookbook, 3rd Edition

David Beazley, Brian K. Jones

Publisher Resources

ISBN: 0596001673Supplemental ContentCatalog PageErrata