在python中解压缩字典

问题描述 投票:-1回答:3

我有如下字典

    dict = {'Sept close adds': close_adds, 'Sept close deletes': close_deletes, 'Sept Changes': annual_changes, 'June Changes': june_changes}

我想从上面的字典中删除键和值'June Changes':june_changes,并将值(june_changes)作为单独的变量,以便稍后在代码中使用。

我已经尝试使用以下代码,但是在维护除june_changes之外的字典时,它不会创建具有我想要的值的新变量。

keys, values = dict.keys(), dict.values()

有人可以帮我吗?

python pandas dictionary iterable-unpacking
3个回答
0
投票

您的代码不会以任何方式影响字典。假设密钥在变量key中,则可以执行以下操作:

value = dict[key]
del dict[key]

0
投票

您可以使用

使用字典d(由于与内置函数冲突,因此不好称呼字典字典,因此从'dict'更改)

d = {'Sept close adds': close_adds, 'Sept close deletes': close_deletes, 'Sept Changes': annual_changes, 'June Changes': june_changes}

# get value
june_changes = d['June Changes']

# delete key
del d ['June Changes']

# Show new dictionary
import pprint
pprint.pprint(d)

更新的字典d

{'Sept Changes': 'annual_changes',
 'Sept close adds': 'close_adds',
 'Sept close deletes': 'close_deletes'}

0
投票

dict.pop做您想要的事

>>> d = {"foo":1, "bar":2}
>>> bar = d.pop("bar")
>>> d
{'foo': 1}
>>> bar
2
© www.soinside.com 2019 - 2024. All rights reserved.