python - A pythonic way to take a dictionary as input and return a sub-dictionary as output -


i looking pythonic way take dictionary , key name input, , return dictionary without key (and associated value) output.

this came far:

def subdict(inputdict,inputkey):     return dict([(key,val) key,val in inputdict.iteritems() if key != inputkey]) 

test case:

print subdict({'a':1,'b':2,'c':3},'b') 

gives:

{'a': 1, 'c': 3} 

are there better suggestions (cleaner and/or simpler code)?

thank you.

well, comprehension might replaced dictionary display:

{key:val key,val in inputdict.iteritems() if key != inputkey} 

but might faster copy , remove, lookup o(1). because of filter, python won't know in advance size of dictionary, , hash table might become costly grow.

def subdict(inputdict, inputkey):     subdict = inputdict.copy()     del subdict[inputkey]     return subdict 

this readable.

if want silently ignore case when inputkey not found, can replace del subdict.pop(inputkey, none). provides default value (which ignore) rather double check.


Comments

Popular posts from this blog

php - Vagrant up error - Uncaught Reflection Exception: Class DOMDocument does not exist -

vue.js - Create hooks for automated testing -

Add new key value to json node in java -