how can I create nested dictionary keys and assign them values from a list of namespaced key value pairs?

red888 :

I have env vars that looks like this:

CONFIG-SOMEKEY-SOMEOTHERKEY = val345
CONFIG-SOMEKEY-SOMEOTHEROTHERKEY = val678
CONFIG-ANOTHERKEY = val222

I want to create a dictionary out of them that would look like:

{
  'SOMEKEY': {
    'SOMEOTHERKEY': 'val3242',
    'SOMEOTHEROTHERKEY': 'val678'
  }
  'ANOTHERKEY': 'val222'
}

"CONFIG-" is a prefix to denote which vars this should be done with- so I can filter them easily like this:

config_fields = [i for i in os.environ if i.startswith("CONFIG-")]

But I'm unsure of how to loop over the string, split on "-" and build a dict.

While looping I was thinking I could check if its the last item and assign the value but how would it know the full path of keys it's on?

I suspect this is a job for recursion I'm just now sure exactly how to implement it

Dani Mesejo :

You could do:

data = ['CONFIG-SOMEKEY-SOMEOTHERKEY = val345',
        'CONFIG-SOMEKEY-SOMEOTHEROTHERKEY = val678',
        'CONFIG-ANOTHERKEY = val222']

result = {}
for e in data:
    key, value = e.split(" = ")  # split into key and value
    path = key.split("-")  # split the key into parts
    ref = result
    for part in path[1:-1]:
        ref[part] = part in ref and ref[part] or {}
        ref = ref[part]
    ref[path[-1]] = value  # take the last part of key and set the value

print(result)

Output

{'SOMEKEY': {'SOMEOTHERKEY': 'val345', 'SOMEOTHEROTHERKEY': 'val678'}, 'ANOTHERKEY': 'val222'}

This part:

ref = result
for part in path[1:-1]:
    ref[part] = part in ref and ref[part] or {}
    ref = ref[part]
ref[path[-1]] = value

will create the nested dictionaries, is equivalent to:

for part in path[1:-1]:
    if part not in ref:
        ref[part] = {}
    ref = ref[part]

So if the part is in the dictionary you set ref as the value corresponding to part otherwise you create a new dictionary.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

How to create a dictionary that contains key‐value pairs from a text file

How to create a dictionary from a list with a list of keys only and key-value pairs (Python)?

How to create a Dictionary with Key/Value pairs in angular?

How can I create a flat dictionary from a nested dictionary whose keys are a subset of a reference dictionary?

Create dictionary key/value pairs from a list based on a condition

How can I create a dictionary of dictionaries of Unique Key Pairs?

How can I assign each varying value of a list to different keys of the same dictionary?

How to assign values in list of list to keys to create dictionary in python

How can I use complex binding to get keys displayed rather then values from key value pairs in view.xml

Is there a way to randomly shuffle keys and values in a Python Dictionary, but the result can't have any of the original key value pairs?

How can I create a dictionary from a list where the keys are the indexes and the values are the actual elements of the list one by one?

How can I create a table from key-value pairs?

How can I customize a nested serialized list of django model objects to be key/value pairs instead?

How can I assign new classes to each item in a list by iterating over a dictionary's key/value pairs based on a matched attribute in python?

How to assign a list with keys and values from a dictionary in Python

Retrieve specific keys and values from a nested dictionary and assign them into a new dictionary in python 3.X

create dictionary of values based on matching keys in list from nested dictionary

how can I randomize the order of a list of keys and value pairs?

How can I get the key value pair to create a dictionary from a nested dictionary?

How can I create a new nested dictionary from an old nested dictionary with updated keys and value?

Create dictionary key and value pair from nested JSON values

How to iterate and append key value pairs from a dictionary within a dicionary and storing values with same key into a list python

Python - How do I take items from a list and assign them to values in a dictionary?

How can I populate the key value pairs of a new dictionary from an existing dictionary?

how to remove key value pairs from a dictionary based on values which are in list format and having some intersection with other list values

Producing key:value pairs from existing pairs in nested dictionary

Nested dictionary with key: list[key:value] pairs to dataframe

Create a dictionary from key value, where the keys and values are pair types

How can I pull keys from a dictionary based on their value and add them to a list?