tnajdek
tnajdek

Reputation: 542

How to add extra key-value pairs to a dict() constructed with a generator argument?

One can create dictionaries using generators (PEP-289):

dict((h,h*2) for h in range(5))
#{0: 0, 1: 2, 2: 4, 3: 6, 4: 8}

Is it syntactically possible to add some extra key-value pairs in the same dict() call? The following syntax is incorrect but better explains my question:

dict((h,h*2) for h in range(5), {'foo':'bar'})
#SyntaxError: Generator expression must be parenthesized if not sole argument

In other words, is it possible to build the following in a single dict() call:

{0: 0, 1: 2, 2: 4, 3: 6, 4: 8, 'foo': 'bar' }

Upvotes: 8

Views: 2610

Answers (3)

Mark Ransom
Mark Ransom

Reputation: 308452

dict([(h,h*2) for h in range(5)] + [(h,h2) for h,h2 in {'foo':'bar'}.items()])

Upvotes: 1

ninjagecko
ninjagecko

Reputation: 91132

Constructor:

dict(iterableOfKeyValuePairs, **dictOfKeyValuePairs)

Example:

>>> dict(((h,h*2) for h in range(5)), foo='foo', **{'bar':'bar'})
{0: 0, 1: 2, 2: 4, 3: 6, 4: 8, 'foo': 'foo', 'bar': 'bar'}

(Note that you will need to parenthesize generator expressions if not the sole argument.)

Upvotes: 16

Gareth McCaughan
Gareth McCaughan

Reputation: 19981

You could use itertools.chain (see Concatenate generator and item) to add your extra stuff into your call to dict().

It's probably clearer to do it the easy way, though: one call to dict and then add the extra items in explicitly.

Upvotes: 0

Related Questions