Extracting a Subset from Dictionary
There are many ways to extract a subset from a dictionary The simplest way is to use a list comprehension.The resulting subset of dict can either leave the input dictionary as it is, or can delete those elements that have been selected. Here is the code for the same
def sub_dict(somedict, somekeys, default = None):
return dict(\[ (k, somedict.get(k, default)) for k in somekeys\])
d = {‘a’:5 ,‘b’:45,‘c’:34}
print sub_dict(d, [‘b’,‘a’])
def sub_dict_remove(somedict, somekeys, default = None):
return dict(\[ (k, somedict.pop(k, default)) for k in somekeys\])
d = {‘a’:5 ,‘b’:45,‘c’:34}
print sub_dict_remove(d, [‘b’,‘a’])
print d
{‘a’: 5, ‘b’: 45}
{‘a’: 5, ‘b’: 45}
{‘c’: 34}
In the above code, there is a possibility that the key you are trying to extract is not there. Instead of raising an exception the above code gives a default value. In most of the cases this might not be what the programmer wants. Here is a version that raises exception for missing key
def sub_dict_strict(somedict, somekeys):
return dict(\[ (k, somedict\[k\]) for k in somekeys\])
d = {‘a’:5 ,‘b’:45,‘c’:34}
print sub_dict(d, [‘b’,‘a’])
def sub_dict_remove(somedict, somekeys):
return dict(\[ (k, somedict.pop(k)) for k in somekeys\])
d = {‘a’:5 ,‘b’:45,‘c’:34}
print sub_dict_remove(d, [‘b’,‘a’])
print d
{‘a’: 5, ‘b’: 45}
{‘a’: 5, ‘b’: 45}
{‘c’: 34}
In case there is an exception, the programmer might not want that key in the returned dictionary. Here is the code which does that by adding an if condition to the list comprehension
def sub_dict_select(somedict, somekeys):
return dict(\[ (k, somedict\[k\]) for k in somekeys if k in somedict\])
d = {‘a’:5 ,‘b’:45,‘c’:34}
print sub_dict(d, [‘b’,‘a’])
def sub_dict_select(somedict, somekeys):
return dict(\[ (k, somedict.pop(k)) for k in somekeys if k in somedict\])
d = {‘a’:5 ,‘b’:45,‘c’:34}
print sub_dict_select(d, [‘b’,‘a’,‘asdasda’])
print d
{‘a’: 5, ‘b’: 45}
{‘a’: 5, ‘b’: 45}
{‘c’: 34}
You can also rewrite the above code using generators.Notice that in the dict function, the argument is a iterator
def sub_dict_select(somedict, somekeys):
return dict( (k, somedict\[k\]) for k in somekeys if k in somedict )
d = {‘a’:5 ,‘b’:45,‘c’:34}
print sub_dict(d, [‘b’,‘a’])
{‘a’: 5, ‘b’: 45}