代码之家  ›  专栏  ›  技术社区  ›  Omnipresent

从字典中获取特定键的方法

  •  3
  • Omnipresent  · 技术社区  · 10 年前

    我正在寻找一种从字典中获取特定键的方法。

    在下面的例子中,我试图 get all keys except 'inside'

    >>> d
    {'shape': 'unchanged', 'fill': 'unchanged', 'angle': 'unchanged', 'inside': 'a->e', 'size': 'unchanged'}
    >>> d_keys = list(set(d.keys()) - set(["inside"]) )
    >>> d_keys
    ['shape', 'fill', 'angle', 'size']
    >>> for key in d_keys:
    ...     print "key: %s, value: %s" % (key, d[key])
    ...
    key: shape, value: unchanged
    key: fill, value: unchanged
    key: angle, value: unchanged
    key: size, value: unchanged
    

    有比上面更好的方法吗?

    8 回复  |  直到 10 年前
        1
  •  4
  •   Mazdak    10 年前

    keys ,返回一个类似集合的视图对象,因此无需再次将其转换为集合:

    >>> d_keys = d.keys() - {"inside",}
    >>> d_keys
    {'fill', 'size', 'angle', 'shape'}
    

    dict.viewkeys() :

    d_keys = d.viewkeys() - {"inside",}
    

    但如果你只想删除一个项目,你可以使用 pop() 属性,以便从字典中删除相应的项,然后调用 keys() .

    >>> d.pop('inside')
    'a->e'
    >>> d.keys()
    dict_keys(['fill', 'size', 'angle', 'shape'])
    

    在python 2中,从 按键() remove() 属性,用于直接从键中移除项。

        2
  •  1
  •   Janarthanan .S    10 年前

    您可以使用内置的remove()。

    d = {'shape': 'unchanged', 'fill': 'unchanged', 'angle': 'unchanged', 'inside': 'a->e', 'size': 'unchanged'}
    
    d_keys = list(d.keys())
    d_keys.remove('inside')
    
    for i in d_keys:
        print("Key: {}, Value: {}".format(d_keys, d[d_keys]))
    
        3
  •  1
  •   Craig Burgler    10 年前

    交叉版本方法:

    d = {'shape': 'unchanged', 'fill': 'unchanged',
        'angle': 'unchanged', 'inside': 'a->e', 'size': 'unchanged'}
    
    d_keys = [k for k in d.keys() if k  != 'inside']
    
    print(d_keys)
    

    输出:

    ['fill', 'shape', 'angle', 'size']
    


    稍微扩展一下:
    def get_pruned_dict(d, excluded_keys):
        return {k:v for k,v in d.items() if k not in excluded_keys}
    
    exclude = ('shape', 'inside')
    pruned_d = get_pruned_dict(d, exclude)
    
    print(pruned_d)
    

    输出

    {'fill': 'unchanged', 'size': 'unchanged', 'angle': 'unchanged'}
    
        4
  •  0
  •   Daniel Lee    10 年前

    不确定你内心需要什么,但这会给你结果。

    for key in d.keys:
        if key != 'inside':
             print "key: %s, value: %s" % (key, d[key])
    
        5
  •  0
  •   Himanshu dua    10 年前
    for key in d_keys:
        if key not in ['inside']:
            print "key: %s, value: %s" % (key, d[key])
    
        6
  •  0
  •   Morgan Thrapp    10 年前

    如果你需要保持原来的字典不变,那么没有一个好方法可以做到这一点。

    如果你不这样做,你可以 pop 在拿到钥匙之前你不想要的钥匙。

    d = {'shape': 'unchanged', 'fill': 'unchanged', 'angle': 'unchanged', 'inside': 'a->e', 'size': 'unchanged'}
    d.pop('inside')
    for key in d.keys():
         print "key: %s, value: %s" % (key, d[key])
    

    这会变异 d ,所以再次强调,如果您需要所有 d 在其他地方。你可以复制 d ,但在这一点上,您最好只迭代 d.keys() 。例如:

    d = {'shape': 'unchanged', 'fill': 'unchanged', 'angle': 'unchanged', 'inside': 'a->e', 'size': 'unchanged'}
    ignored_keys = ['inside']
    for key in filter(lambda x: x not in ignored_keys, d.keys()):
         print "key: %s, value: %s" % (key, d[key])
    
        7
  •  0
  •   BPL    10 年前

    这里有一个比较两个好的发布解决方案的小基准:

    import timeit
    
    d = {'shape': 'unchanged', 'fill': 'unchanged',
         'angle': 'unchanged', 'inside': 'a->e', 'size': 'unchanged'}
    
    
    def f1(d):
        return d.viewkeys() - {"inside", }
    
    
    def f2(d):
        return filter(lambda x: x not in ['inside'], d.viewkeys())
    
    N = 10000000
    print timeit.timeit('f1(d)', setup='from __main__ import f1, d', number=N)
    print timeit.timeit('f2(d)', setup='from __main__ import f2, d', number=N)
    
    # 5.25808963984
    # 8.54371443087
    # [Finished in 13.9s]
    

    结论:f1不仅可读性更好,而且性能也更好。在python 3.x中,您应该使用keys()。

    所以我想说@Kasramvd答案是这个帖子的正确答案

        8
  •  -1
  •   Mike Tung    10 年前

    例如,你可以用dict理解来做,只得到平均值。

    d = {1:'a', 2:'b', 3:'c', 4:'d'}
    new_d = {k : v for k,v in d.items() if k % 2 == 0}
    

    d = {'shape': 'unchanged', 'fill': 'unchanged', 'angle': 'unchanged',         'inside': 'a->e'}
    new_d = {k:v for k,v in d.items() if k != 'fill'}
    #you can replace the k != with whatever key or keys you want