Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

syntax

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' }
like image 384
tnajdek Avatar asked Apr 30 '12 21:04

tnajdek


People also ask

How do you add multiple key-value pairs to a dictionary?

In Python, we can add multiple key-value pairs to an existing dictionary. This is achieved by using the update() method. This method takes an argument of type dict or any iterable that has the length of two - like ((key1, value1),) , and updates the dictionary with new key-value pairs.

Is dict () and {} the same?

As we can see, dict() is obviously slower than {}. Especially, if the dictionary is initialized with many elements, it has a huge impact if your code needs 0.04ms or almost 0.08ms to create your dictionary. Even when you initialize an empty dictionary, it is slower.

What does dict keys () do in Python?

Python Dictionary keys() method The keys() method in Python Dictionary, returns a view object that displays a list of all the keys in the dictionary in order of insertion using Python. Parameters: There are no parameters. Returns: A view object is returned that displays all the keys.

How do you assign multiple values to one key in Python?

In python, if we want a dictionary in which one key has multiple values, then we need to associate an object with each key as value. This value object should be capable of having various values inside it. We can either use a tuple or a list as a value in the dictionary to associate multiple values with a key.


2 Answers

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.)

like image 104
ninjagecko Avatar answered Sep 23 '22 17:09

ninjagecko


dict([(h,h*2) for h in range(5)] + [(h,h2) for h,h2 in {'foo':'bar'}.items()])
like image 30
Mark Ransom Avatar answered Sep 23 '22 17:09

Mark Ransom