python,使用理解有选择地将值从一个字典弹出到另一个字典
python, selectively pop values from one dictionary into another using comprehension
如何将这里的这个函数转换成字典理解?可能吗?
info['dict1'] = {}
dict2 = {'one': 1}
for x in ['one', 'two']:
info['dict1'].update({x:dict2.pop(x, None)})
这是我尝试过的方法,但效果不佳,似乎什么也没有发生。信息保持为空:
(info['dict1'].update({x:dict2.pop(x)}) for x in ['one', 'two'])
打印输出显示信息为空... {'dict1': {}}
当然是:
info['dict1'] = {x: dict2.pop(x, None) for x in ['one', 'two']}
不要对副作用使用理解;他们首先产生一个列表、集合或字典。在上面的代码中,info['dict1']
的 new 字典对象由字典理解生成。
如果您有更新现有字典,请使用dict.update()
和生成键值对的生成器表达式:
info['dict1'].update((x, dict2.pop(x, None)) for x in ['one', 'two'])
您可以创建 info
with dict with the key 并使用 dict comp ad the value。
dict2 = {'one': 1}
info = {'dict1': {x: dict2.pop(x, None) for x in ['one', 'two']} }
print(info)
如何将这里的这个函数转换成字典理解?可能吗?
info['dict1'] = {}
dict2 = {'one': 1}
for x in ['one', 'two']:
info['dict1'].update({x:dict2.pop(x, None)})
这是我尝试过的方法,但效果不佳,似乎什么也没有发生。信息保持为空:
(info['dict1'].update({x:dict2.pop(x)}) for x in ['one', 'two'])
打印输出显示信息为空... {'dict1': {}}
当然是:
info['dict1'] = {x: dict2.pop(x, None) for x in ['one', 'two']}
不要对副作用使用理解;他们首先产生一个列表、集合或字典。在上面的代码中,info['dict1']
的 new 字典对象由字典理解生成。
如果您有更新现有字典,请使用dict.update()
和生成键值对的生成器表达式:
info['dict1'].update((x, dict2.pop(x, None)) for x in ['one', 'two'])
您可以创建 info
with dict with the key 并使用 dict comp ad the value。
dict2 = {'one': 1}
info = {'dict1': {x: dict2.pop(x, None) for x in ['one', 'two']} }
print(info)