Python 保留除一个键以外的所有条目

Python 保留除一个键以外的所有条目,python,Python,我有一本python字典。为了给出上下文,我正在尝试编写自己的简单交叉验证单元 所以基本上我想要的是得到所有的值,除了给定的键。 根据输入,它返回字典中的所有值,除了给定的值 因此,如果输入是2和5,那么输出值没有键2和键5的值 for key, value in your_dict.items(): if key not in your_blacklisted_set: print value 美妙之处在于,这个伪代码示例是有效的python代码 它也可以表示为列表理

我有一本python字典。为了给出上下文,我正在尝试编写自己的简单交叉验证单元

所以基本上我想要的是得到所有的值,除了给定的键。 根据输入,它返回字典中的所有值,除了给定的值

因此,如果输入是2和5,那么输出值没有键2和键5的值

for key, value in your_dict.items():
    if key not in your_blacklisted_set:
        print value
美妙之处在于,这个伪代码示例是有效的python代码

它也可以表示为列表理解:

resultset = [value for key, value in your_dict.items() if key not in your_blacklisted_set]

以下几点怎么样:

In [7]: d = dict((i,i+100) for i in xrange(10))

In [8]: d
Out[8]: 
{0: 100,
 1: 101,
 2: 102,
 3: 103,
 4: 104,
 5: 105,
 6: 106,
 7: 107,
 8: 108,
 9: 109}

In [9]: exc = set((2, 5))

In [10]: for k, v in d.items():
   ....:     if k not in exc:
   ....:         print v
   ....:         
   ....:         
100
101
103
104
106
107
108
109

此外,作为使用集合的列表理解:

d = dict(zip(range(9),"abcdefghi"))
blacklisted = [2,5]
outputs = [d[k] for k in set(d.keys())-set(blacklisted)]
给一本字典说

d = {
     2: 2, 5: 16, 6: 5,
     7: 6, 11: 17, 12: 9,
     15: 18, 16: 1, 18: 16,
     19: 17, 20: 10
     }
然后,简单的理解示例将实现您可能想要的

[v for k,v in d.iteritems() if k not in (2,5)]
此示例列出了所有不带键{2,5}的值

例如,上述理解的O/p为

[5, 6, 1, 17, 9, 18, 1, 16, 17, 10]
只是为了好玩而已

keys = set(dict.keys())
excludes = set([...])

for key in keys.difference(excludes):
    print dict[key]

弹出要丢弃的键后,dict将保留您要查找的键。

如果您的目标是返回一个新字典,其中包含除一个或几个键/值之外的所有键/值,请使用以下命令:

exclude_keys = ['exclude', 'exclude2']
new_d = {k: d[k] for k in set(list(d.keys())) - set(exclude_keys)}

其中,
'exclude'
可以被应排除的(一系列)键替换。

使用异常处理

facebook_posts = [
    {'Likes': 21, 'Comments': 2}, 
    {'Likes': 13, 'Comments': 2, 'Shares': 1}, 
    {'Likes': 33, 'Comments': 8, 'Shares': 3}, 
    {'Comments': 4, 'Shares': 2}, 
    {'Comments': 1, 'Shares': 1}, 
    {'Likes': 19, 'Comments': 3}
]

total_likes = 0

for post in facebook_posts:
    try:
        total_likes = total_likes + post['Likes']
    except KeyError:
        pass
print(total_likes)
您还可以使用:

except KeyError: 'My Key'

但可能只适合一次性使用。。可能是个愚蠢的问题。。但是我的黑名单集是什么呢?[2,5]在你给出的示例中,它是你想要排除的键列表。
[d[k]表示集合中的k(d.keys())。差异(set(excludes))]
不要使用
dict
作为名称。小的改进:直接将排除键初始化为一个集合:
排除键={'exclude',exclude2}
except KeyError: 'My Key'