动态地读写字典



我正在尝试从字典中读取值,然后写入另一个。

以下作品,但是硬编码

    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

我想做的是从和列表中传递的(因为我将有很多(。

我想象的输入将是这样的

{"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"}]}

在这种情况下,它将进行以上两次(检查现有词典等(。我对检查等都很好,这是使用上述我被卡在上面的方法。

任何帮助将不胜感激

谢谢

您可以使用defaultdict,但是在执行此操作时需要考虑一些特殊的事情。如果您读取不存在的值,它将为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

荣誉:如何使Python在字典中自动创建缺少的键/值对?

最新更新