Skip to content

Instantly share code, notes, and snippets.

@mzpqnxow
Created November 26, 2020 17:24
Show Gist options
  • Save mzpqnxow/328118cc427342b1bb0305e10ba2e572 to your computer and use it in GitHub Desktop.
Save mzpqnxow/328118cc427342b1bb0305e10ba2e572 to your computer and use it in GitHub Desktop.
name_value_consolidate_to_true_dict.py
def kv_pair_list_to_map(self, obj, name_key, value_key='value'):
"""Return a dictionary from a list of fixed name/value keyed dicts
This handles the common "xml-style" storage of values in JSON
It also merges into lists as appropriate
Example Usage (for below input)
===============================
map_obj = kv_pair_list_to_map(obj, 'var_name', value_key='value')
Example Input
=============
[
{"var_name": "height", "value": 100},
{"var_name": "weight", "value": 150},
{"var_name": "age", "value": 51 }
]
Example Output
==============
{
'height': 100,
'weight': 150,
'age': 51}
}
TODO: Support duplicates, convert them to arrrays
Handle input like this:
{"var_name": "category", "value": "ecommerce"},
{"var_name": "category", "value": "retail"},
{"var_name": "name", "value": "Target }
And return:
{
"category": [
"ecommerce",
"retail"],
name: "Target"
}
This isn't difficult, it just makes this less one-line friendly
"""
return dict(map(lambda item: (item[name_key], item[value_key]), obj))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment