[英]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': {}}
打印输出显示信息保持空白...
{'dict1': {}}
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. 在上面的代码中,字典理解产生了一个新的
info['dict1']
字典对象。
If you have to update an existing dictionary, use dict.update()
with a generator expression producing key-value pairs: 如果必须更新现有字典,请将
dict.update()
与生成键值对的生成器表达式一起使用:
info['dict1'].update((x, dict2.pop(x, None)) for x in ['one', 'two'])
You can create info
with dict with the key and use a dict comp ad the value. 您可以使用键通过dict创建
info
,并使用dict comp ad作为值。
dict2 = {'one': 1}
info = {'dict1': {x: dict2.pop(x, None) for x in ['one', 'two']} }
print(info)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.