在 for 循环中插入和删除字典 - 最佳方法?



我有一个字典,看起来像这样:

{attribute_1 : True,
attribute_2 : False,
attribute_3 : 'foo', # Can be one of multiple text options here
attribute_4 : 5,}    # Can be one of multiple numerical options here

我需要转换它,以便每个值都是布尔值,从而得到:

{attribute_1 : True,
attribute_2 : False,
attribute_3_foo : True,
attribute_4_5 : True}

(用于机器学习的独热编码,以防有人关心我为什么要做这么奇怪的事情。 将处理很多很多这样的词典...

我发现的一个可行的解决方案是通过字典执行 for 循环以寻找非布尔值,并 (1( 创建新条目,然后 (2( 删除任何带有非布尔键的内容。 这很好,但它看起来不优雅且内存效率低下,因为我的列表是内存中的新对象。 有没有更好的方法可以做到这一点?

# List loop to insert ('k,v in dict' won't let you add/delete items)
for x in list(sub_d.items()):
if type(x[1]) is not bool:
sub_d[x[0]+'_'+ str(x[1])] = True
del sub_d[x[0]]

列表推导不起作用,因为我找不到一种方法来输入足够复杂的操作来完成工作。 另外,我认为他们不会比我当前的解决方案有任何效率提升?

您可以使用dict理解:

d = {k if isinstance(v, bool) else '{}_{}'.format(k, v): bool(v) 
for k, v in d.items()} 
{'attribute_1': True,
'attribute_2': False,
'attribute_3_foo': True,
'attribute_4_5': True}

插入的列表循环(字典中的"k,v"不允许您添加/删除项目(

for x in list(sub_d.items()):
if type(x[1]) is not bool:
sub_d[x[0]+'_'+ str(x[1])] = True
del sub_d[x[0]]

为什么不只是:

for x in dic:
if type(x) is not bool:
dic[x] = True

没有理由删除条目,这将在 O(n( 时间内运行,因为dic是一个哈希表。

最新更新