Python 从字典中获取特定键的方法
我正在寻找一种从字典中获取特定键的方法 在下面的示例中,我试图Python 从字典中获取特定键的方法,python,dictionary,Python,Dictionary,我正在寻找一种从字典中获取特定键的方法 在下面的示例中,我试图获取除“inside”之外的所有密钥 >>> d {'shape': 'unchanged', 'fill': 'unchanged', 'angle': 'unchanged', 'inside': 'a->e', 'size': 'unchanged'} >>> d_keys = list(set(d.keys()) - set(["inside"]) ) >>> d_k
获取除“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
有没有比上面更好的方法呢?你可以通过听写理解来做到这一点,例如,你只需要获得平衡
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
如果你需要保持原来的字典不变的话,没有什么好方法可以做到这一点
如果不需要,您可以在拿到钥匙之前弹出您不想要的钥匙
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])
在Python3.X中,大多数字典属性(如keys
)都返回一个类似于set的视图对象,因此无需再次将其转换为set:
>>> d_keys = d.keys() - {"inside",}
>>> d_keys
{'fill', 'size', 'angle', 'shape'}
或者,如果您使用的是python2.x,则可以使用dict.viewkeys()
:
但是如果您只想删除一个项目,可以使用pop()
属性从字典中删除相应的项目,然后调用keys()
在python 2中,由于keys()
返回一个列表对象,因此可以使用remove()
属性直接从键中删除项 不确定你需要什么,但这会给出你的结果
for key in d.keys:
if key != 'inside':
print "key: %s, value: %s" % (key, d[key])
跨版本方法:
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'}
这里有一个比较两个好的发布解决方案的小基准:
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不仅在可读性方面更好,而且在性能方面也更好。在Python3.x中,您将使用keys()代替
所以我想说@Kasramvd answer是这篇文章的正确答案您可以使用内置的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]))
为什么要设置(d.keys())
?键应该是唯一的,因为你不能使用其他的集合运算。我想这应该是一个不同的问题。为什么?如果重点是根据标准过滤字典,那么这就解决了问题,因为OP的字典不是一组编号键。我知道这项技术是可以推广的,但答案应该可以解决问题中的具体问题。只需修改它以明确回答@MorganThrapp,如果你在做pop,他将有开销,因为pop
可能会导致一个空的dict并抛出一个弹出空dict的错误。或者,创建一个类似ignore的列表=['inside',]
,然后如果key not in ignore…
这是处理多个特殊键时更通用的解决方案。您应该使用{}
和format string方法,而不是%s
它更像python。更不用说使用d.keys()
这里很浪费,因为你可以很容易地用d.items()
得到key:value的元组。如果你弹出,你应该提供一个None
的参数,以避免一些开销。当我在Python 3中运行这段代码时(将viewkeys
更改为keys
),f2
比f1
的速度要快很多。当我在Python 2中以不变的方式运行它时,我还认为f1
的速度更快,从而确认了您在Python 2中的结果。
{'fill': 'unchanged', 'size': 'unchanged', 'angle': 'unchanged'}
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]
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]))