为什么删除键a和键c,而不只是键c?

时间:2012-06-13 22:23:49

标签: python

我正在开发一个程序来从字典中的列表中删除空白值,但是如果整个值只包含一个只包含单个空格的数组,我需要删除包含单个空格的元素。

def CleanWhiteSpace(theDict) :
    stuff=[]
    for key2 in theDict.keys():
        for value2 in theDict.values(): 
            if value2 == [' ']:
                print key2
                del theDict[key2]
                print "hi"

    print theDict
    for key,value in theDict.iteritems():
        for d in value:
            print value
            if d != ' ':
                    stuff.append(d)    
            theDict[key]=stuff
        stuff=[]

    return theDict
print CleanWhiteSpace({'a':['1','2'],'b':['3',' '],'c':[' ']})

我只想删除密钥c。

5 个答案:

答案 0 :(得分:3)

对于每个键,您只应查看单个值,而不是循环遍历theDict.values()

def CleanWhiteSpace(theDict) :
    stuff=[]
    for key2 in theDict.keys():  # this is the line I changed
        if theDict[key2] == [' ']:
            print key2
            del theDict[key2]
            print "hi"

    print theDict
    for key, value in theDict.iteritems():
        for d in value:
            print value
            if d != ' ':
                    stuff.append(d)
            theDict[key]=stuff
        stuff=[]

    return theDict
print CleanWhiteSpace({'a':['1','2'],'b':['3',' '],'c':[' ']})

答案 1 :(得分:2)

您的嵌套循环

for key2 in theDict.keys():
    for value2 in theDict.values(): 
        if value2 == [' ']:
            print key2
            del theDict[key2]
            print "hi"

遍历每个键的所有值。结果取决于字典决定返回键的顺序 - 如果最后访问键"c",您甚至可能会得到一个空字典。

您想要的是以下内容(Python 2.x):

for key, value in theDict.items():
    if value == [" "]:
        del theDict[key]

您是否还需要删除仅包含两个空间条目的值?在这种情况下,首先删除空格会更容易,然后删除所有空列表:

d = {}
for key, value in theDict.iteritems():
    d[key] = [x for x in value if x != " "]
return {k: v for k, v in d.iteritems() if v}

答案 2 :(得分:2)

其他人已经指出了现有代码中的问题,但是,有一个更好的解决方案可以解决这个问题:

{key: values for key, values in ((key, [item for item in values if not item == " "]) for key, values in data.items()) if values}

这里我们使用dict and list comprehensions, along with a generator expression的组合。我们首先使用生成器表达式来获取每个字典项,并从列表中删除任何单个空格字符串。然后我们使用dict理解从这些数据重建字典,忽略任何具有空值的项目(它们都已被删除)。

与往常一样,请在2.x中使用dict.iteritems()dict.viewitems()

编辑:如果你不喜欢巨大的代码,请记住你可以把它分开。

def strip_items(items, strip):
    return [item for item in values if not item == strip]
stripped = ((key, strip_items(values, " ")) for key, values in data.items())
new_data = {key: values for key, values in stripped if values}

答案 3 :(得分:2)

试试这个:

def CleanWhiteSpace(entries):
    blank_keys = [key for key in entries if all([' ' == value for value in entries[key]])]
    for key in blank_keys:
        del entries[key]
    return entries


print CleanWhiteSpace({'a':['1','2'],'b':['3',' '],'c':[' ']})

答案 4 :(得分:2)

不知道为什么你的功能不起作用,但这是一个较短的方法:

clean = {k: v for k, v in dct.items() if ''.join(v).strip()}

例如:

dct = {'a':['1','2'],'b':['3',' '],'c':[' ']}
clean = {k: v for k, v in dct.items() if ''.join(v).strip()}
print clean # {'a': ['1', '2'], 'b': ['3', ' ']}