【问题标题】:Reading and writing to a dictionary dynamically动态读取和写入字典
【发布时间】:2019-05-14 14:48:37
【问题描述】:

我正在尝试从字典中读取值,然后写入不同的值。

以下工作,但是是硬编码的

    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

不过,我想做的是传入一个 from 和 to 列表(因为我会有很多这样的)。

我想象输入会是这样的

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

在这种情况下,它将执行上述两次(检查现有字典等)。我在检查等方面很好,这是我卡在上面的如何使用。

任何帮助将不胜感激

谢谢

【问题讨论】:

  • 查看jsonpath

标签: python-3.x


【解决方案1】:

您可以使用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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-03-19
    • 2015-01-17
    • 2022-01-08
    • 1970-01-01
    • 1970-01-01
    • 2014-01-31
    • 1970-01-01
    • 2022-01-07
    相关资源
    最近更新 更多