Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using dict keys in python as values in a different dict

I would like to create a "translator" type of dict that would assign values that are keys in different dicts, which are nested, to keys in a dict that I created. The problem I run into is that I can't create a value that represents a nested dict key without having to convert that to a string or some other data type, and when I try to use a string as an index to the nested dict, I get an index error. Ideally, my dict would look something like this:

new_dict{
    "new_key_1" : ['subdict1']['subdict2']['old_key_1'],
    "new_key_2" : ['subdict1']['subdict2']['old_key_2'],
    "new_key_3" : ['subdict1']['subdict3']['old_key_3']
    }

Then, for each nested dict, I could generate a new dict object with a simple for loop:

for key, value in new_dict.items() :
    user_dict_1[key] = OldDict[value]

The nested dicts are very large and I only need a few fields from each, otherwise I could just use the .copy() function to work with the old dicts.

PS- Any help in rewriting this question to be more readable also appreciated.

like image 419
paulski Avatar asked Jan 01 '26 19:01

paulski


1 Answers

You're going to need reduce() for this one...

attrmap = {
  "new_key_1": ('subdict1', 'subdict2', 'old_key_1'),
   ...
}

print reduce(lambda x, y: x[y], attrmap[somekey], old_object)
like image 165
Ignacio Vazquez-Abrams Avatar answered Jan 05 '26 06:01

Ignacio Vazquez-Abrams



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!