如何删除留在另一个str中的字典对象(字母)?

时间:2016-07-17 07:07:38

标签: python python-2.7 dictionary

假设我有这本词典:

x = {'a':2, 'b':5, 'g':7, 'a':3, 'h':8}`

这个输入字符串:

y = 'agb'

我想删除x中出现的y的键,例如,如果我的输入如上,则输出应为:

{'h':8, 'a':3}

我目前的代码在这里:

def x_remove(x,word):
   x1 = x.copy()   # copy the input dict
      for i in word:   # iterate all the letters in str           
          if i in x1.keys():
              del x1[i]    
   return x1

但是当代码运行时,它会删除与word中的字母类似的所有现有键。但我希望尽管有许多类似于字母的键,它只删除一个键而不是每个

如果我错了,我可能会这样做但只是解释我如何在不使用del函数的情况下做到这一点

3 个答案:

答案 0 :(得分:1)

你很接近,但试试这个:

def x_remove(input_dict, word):
    output_dict = input_dict.copy()

    for letter in word:        
        if letter in output_dict:
            del output_dict[letter]

    return output_dict

例如:

In [10]: x_remove({'a': 1, 'b': 2, 'c':3}, 'ac')
Out[10]: {'b': 2}

一个问题是你的缩进。缩进在Python中很重要,并且以{}以及;在其他语言中的方式使用。另一个是你检查每个字母是否在列表中的方式;您希望if letter in output_dict in上的dict() del搜索密钥。

当您使用描述性变量名称时,也更容易看到发生了什么。

我们也可以完全跳过def x_remove(input_dict, word): return {key: value for key, value in input_dict if key not in word} 并使用dict comprehension使其更加Pythonic:

'a'

这仍将隐式创建列表的浅表副本(没有删除的元素)并返回它。这样性能也会更高。

如评论中所述,词典中的所有键都是唯一的。只能有一个名为b或{{1}}的密钥。

答案 1 :(得分:1)

词典必须有唯一的键。您可以使用元组列表代替数据。

x = [('a',2), ('b',5), ('g',7), ('a',3), ('h',8)]

以下代码然后删除所需的条目:

for letter in y:
    idx = 0
    for item in x.copy():   
        if item[0] == letter:
            del x[idx]
            break
        idx += 1

结果:

>>> x
[('a', 3), ('h', 8)]

答案 2 :(得分:0)

你也可以实现像

def remove_(x,y)
    for i in y:
        try:
           del x[i]
        except:
           pass
    return x

输入x = {'a': 1, 'b': 2, 'c':3}y = 'ac'

<强>输出

{'b': 2}