0

I am trying to read value from dictionary and then write to a different one.

The following works, but is hardcoded

    this_application['bounces'] = {}
    this_application['bounces']['month'] = {}
    this_application['bounces']['month']['summary'] = {}
    try:
        got_value = application.ga_data['ga:bounces']['ga:month']['summary']['recent']
    except:
        got_value = ""
    this_application['bounces']['month']['summary']['recent'] = got_value

What I want to do though, is pass in a from and to list (as I will have lots of these).

I was imagining the input would be something like this

{"ga_data": [{"from": "ga:bounces.ga:month.summary.recent", "to": "bounces.month.summary.recent"},{"from": "ga:sessions.ga:month.summary.recent", "to": "sessions.month.summary.recent"}]}

In which case it would do the above twice (with checking for existing dictionaries etc). I am fine on the checking etc., it is how to use the above that I am stuck on.

Any help would be appreciated

Thanks

mozman2
  • 911
  • 1
  • 8
  • 17

1 Answers1

0

You can use defaultdict but there are some special things to consider when doing it. If you read a value that does not exist it will add an empty value to the dict.

import collections
nested_dict = lambda: collections.defaultdict(nested_dict)

d = nested_dict()
d[1][2][3] = 'Hello, dictionary!'
print(d[2]) # I read the value and thus added the key to the dict
print(d[1][2][3]) # Prints Hello, dictionary!
print(d.keys()) # Shows that [1, 2] are keys

Credit To: How can I get Python to automatically create missing key/value pairs in a dictionary?