user1539348
user1539348

Reputation: 513

python, selectively pop values from one dictionary into another using comprehension

How do I convert this function here into a dictionary comprehension? is it possible?

info['dict1'] = {}
dict2 = {'one': 1}

for x in ['one', 'two']:
    info['dict1'].update({x:dict2.pop(x, None)})

Here is what I tried it didn't work very well, nothing seem to happen. info stays empty:

(info['dict1'].update({x:dict2.pop(x)}) for x in ['one', 'two'])

The print output shows that info stays empty ... {'dict1': {}}

Upvotes: 0

Views: 1275

Answers (2)

Martijn Pieters
Martijn Pieters

Reputation: 1124040

Sure it is:

info['dict1'] = {x: dict2.pop(x, None) for x in ['one', 'two']}

Don't use comprehensions for side effects; they produce a list, set or dictionary first and foremost. In the code above, a new dictionary object for info['dict1'] is produced by a dictionary comprehension.

If you have to update an existing dictionary, use dict.update() with a generator expression producing key-value pairs:

info['dict1'].update((x, dict2.pop(x, None)) for x in ['one', 'two'])

Upvotes: 2

Padraic Cunningham
Padraic Cunningham

Reputation: 180482

You can create info with dict with the key and use a dict comp ad the value.

dict2 = {'one': 1}
info = {'dict1': {x: dict2.pop(x, None) for x in ['one', 'two']} }
print(info)

Upvotes: 1

Related Questions