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

时间:2018-09-22 19:30:51

标签: python python-3.x dictionary

我有一个像这样的字典:

{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}

(一种用于机器学习的热编码,以防万一有人在乎我为什么做这种奇怪的事情。将处理许多这样的词典...)。

我发现一个可行的解决方案是在dict上进行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]]

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

2 个答案:

答案 0 :(得分:0)

  

要插入的列表循环(“ dict中的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是哈希表。

答案 1 :(得分: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}