python字典返回键值对_从Python字典对象中提取键值对的子集?

好吧,这件事让我困扰了几次,所以谢谢你Jayesh的提问。

上面的答案看起来像任何一个好的解决方案,但如果你在你的代码中使用这个,那么包装功能恕我直言是有意义的。 此外,这里有两种可能的用例:一种是您关心所有关键字是否都在原始字典中。 还有一个你没有的地方。 平等对待两者都会很好。

因此,对于我的两个百分之一的价值,我建议写一个字典的子类,例如

class my_dict(dict):

def subdict(self, keywords, fragile=False):

d = {}

for k in keywords:

try:

d[k] = self[k]

except KeyError:

if fragile:

raise

return d

现在你可以拿出一个子词典orig_dict.subdict(keywords)

用法示例:

#

## our keywords are letters of the alphabet

keywords = 'abcdefghijklmnopqrstuvwxyz'

#

## our dictionary maps letters to their index

d = my_dict([(k,i) for i,k in enumerate(keywords)])

print('Original dictionary:\n%r\n\n' % (d,))

#

## constructing a sub-dictionary with good keywords

oddkeywords = keywords[::2]

subd = d.subdict(oddkeywords)

print('Dictionary from odd numbered keys:\n%r\n\n' % (subd,))

#

## constructing a sub-dictionary with mixture of good and bad keywords

somebadkeywords = keywords[1::2] + 'A'

try:

subd2 = d.subdict(somebadkeywords)

print("We shouldn't see this message")

except KeyError:

print("subd2 construction fails:")

print("\toriginal dictionary doesn't contain some keys\n\n")

#

## Trying again with fragile set to false

try:

subd3 = d.subdict(somebadkeywords, fragile=False)

print('Dictionary constructed using some bad keys:\n%r\n\n' % (subd3,))

except KeyError:

print("We shouldn't see this message")

如果您运行以上所有代码,您应该看到(类似)以下输出(抱歉格式化):

原始字典:

{'a':0,'c':2,'b':1,'e':4,'d':3,'g':6,'f':5,           'i':8,'h':7,'k':10,'j':9,'m':12,'l':11,'o':14,           'n':13,'q':16,'p':15,'s':18,'r':17,'u':20,           't':19,'w':22,'v':21,'y':24,'x':23,'z':25}

奇数键的字典:

{'a':0,'c':2,'e':4,'g':6,'i':8,'k':10,'m':12,'o':14,' q':16,'s':18,'你':20,'w':22,'y':24}

subd2构造失败:

原始字典不包含一些键

使用一些坏键构造的字典:

{'b':1,'d':3,'f':5,'h':7,'j':9,'l':11,'n':13,'p':15,' r':17,'t':19,'v':21,'x':23,'z':25}

你可能感兴趣的:(python字典返回键值对)