Retain all entries except for one key python

后端 未结 7 581
情书的邮戳
情书的邮戳 2020-12-10 10:16

I have a python dictionary. Just to give out context, I am trying to write my own simple cross validation unit.

So basically what I want is to get all the values exc

相关标签:
7条回答
  • 2020-12-10 10:30

    If your goal is to return a new dictionary, with all key/values except one or a few, use the following:

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

    where 'exclude' can be replaced by (a list of) key(s) which should be excluded.

    0 讨论(0)
  • 2020-12-10 10:33

    Also, as a list comprehension using sets:

    d = dict(zip(range(9),"abcdefghi"))
    blacklisted = [2,5]
    outputs = [d[k] for k in set(d.keys())-set(blacklisted)]
    
    0 讨论(0)
  • 2020-12-10 10:34

    Just for fun with sets

    keys = set(dict.keys())
    excludes = set([...])
    
    for key in keys.difference(excludes):
        print dict[key]
    
    0 讨论(0)
  • 2020-12-10 10:34
    keys = ['a', 'b']
    a_dict = {'a':1, 'b':2, 'c':3, 'd':4}
    [a_dict.pop(key) for key in keys]
    

    After popping out the keys to be discarded, a_dict will retain the ones you're after.

    0 讨论(0)
  • 2020-12-10 10:39

    Given a dictionary say

    d = {
         2: 2, 5: 16, 6: 5,
         7: 6, 11: 17, 12: 9,
         15: 18, 16: 1, 18: 16,
         19: 17, 20: 10
         }
    

    then the simple comprehension example would attain what you possibly desire

    [v for k,v in d.iteritems() if k not in (2,5)]
    

    This example lists all values not with keys {2,5}

    for example the O/P of the above comprehension is

    [5, 6, 1, 17, 9, 18, 1, 16, 17, 10]
    
    0 讨论(0)
  • 2020-12-10 10:41
    for key, value in your_dict.items():
        if key not in your_blacklisted_set:
            print value
    

    the beauty is that this pseudocode example is valid python code.

    it can also be expressed as a list comprehension:

    resultset = [value for key, value in your_dict.items() if key not in your_blacklisted_set]
    
    0 讨论(0)
提交回复
热议问题