Extracts one or more keys ('keys' can be a string or list of strings) from the dictionary 'doc'. Return a subset of 'doc' with only the 'keys' specified as members, all other data in the dictionary will be filtered out. Return an empty dict if no keys are found.
(doc, keys)
| 98 | |
| 99 | |
| 100 | def get_kvps(doc, keys): |
| 101 | """ |
| 102 | Extracts one or more keys ('keys' can be a string or list of strings) |
| 103 | from the dictionary 'doc'. |
| 104 | |
| 105 | Return a subset of 'doc' with only the 'keys' specified as members, all |
| 106 | other data in the dictionary will be filtered out. |
| 107 | Return an empty dict if no keys are found. |
| 108 | """ |
| 109 | if not isinstance(keys, list): |
| 110 | keys = [keys] |
| 111 | |
| 112 | new_doc = {} |
| 113 | for key in keys: |
| 114 | value = get_value(doc, key) |
| 115 | if value is not None: |
| 116 | nested = new_doc |
| 117 | while "." in key: |
| 118 | attr = key[: key.index(".")] |
| 119 | if attr not in nested: |
| 120 | nested[attr] = {} |
| 121 | nested = nested[attr] |
| 122 | key = key[key.index(".") + 1 :] |
| 123 | nested[key] = value |
| 124 | |
| 125 | return new_doc |