-4

I have predefined dictionaries and I need a function to form one dictionary out of several input dicts where the keys are the names of the input dictionaries.

For example, I have the following:

double_left = {
    'left': 6
}

double_right = {
    'right': 6
}

The output should be:

>>> output_dicts
{'double_left': {'left': 6}, 'double_right': {'right': 6}}

I already tried: How do you create nested dict in Python? but could not derive the answer.

Suggestions ?

criticalth
  • 398
  • 2
  • 9
  • 16
  • Please show what you mean by "tried". – Scott Hunter Apr 07 '19 at 16:11
  • 1
    Your question is unclear. How would you choose which dicts to include in your final one? If you want to start with a list of their names, you'd better create a dict in the first place in order to structure your data, rather than having similar but unrelated variables. – Thierry Lathuille Apr 07 '19 at 16:11
  • 1
    You can do literally: `{'double_left': double_left, 'double_right': double_right}`. – ForceBru Apr 07 '19 at 16:14

4 Answers4

3

If you want to do it dynamically without hardcoding the names of the top-level items, you can get a list of variables by names using globals() and/or locals(). For example:

output = {}
for name, val in globals().items():
    # Skipping variables that aren't dicts, and special
    # variables starting with '_'
    if isinstance(val, dict) and not name.startswith('_'):
        output[name] = val

for name, val in locals().items():
    if isinstance(val, dict) and not name.startswith('_'):
        output[name] = val

Or more compact:

output = {name:val for name, val in (list(locals().items()) +
                                     list(globals().items()))
          if isinstance(val, dict) and not name.startswith('_')}
almiki
  • 455
  • 2
  • 4
2

Just make a new dictionary.

output_dict = {"double_left": double_left, "double_right": double_right}
print(output_dict)
ruohola
  • 21,987
  • 6
  • 62
  • 97
Sandeep Polamuri
  • 609
  • 4
  • 10
  • Can you make that a function that takes only the dictionaries as inputs ? how can you make the dictionary name a string ? – criticalth Apr 07 '19 at 16:19
  • 1
    @criticalth, you can't: https://stackoverflow.com/questions/18425225/getting-the-name-of-a-variable-as-a-string – ruohola Apr 07 '19 at 16:23
0

Just like your current dicts have 'key': 'value' pairs, with your values being ints (6), you can create a new dict with the keys being the name of the dict and the values being the nested dict.

output_dicts = {'double_left': double_left, 'double_right': double_right}

>>> output_dicts
{'double_left': {'left': 6}, 'double_right': {'right': 6}}

You can also use dict_name[new_key] = new_value. For example:

output_dicts['double_left'] = double_left
output_dicts['double_right'] = double_right
JDog
  • 1
  • 1
0

Try this

Newdict = dict(double_left = { 'left': 6},double_right = 
{'right': 6})