【问题标题】:Access a dictionary at an array of keys, or initialize the key as a subdictionary在键数组中访问字典,或将键初始化为子字典
【发布时间】:2017-10-23 11:28:50
【问题描述】:

我有一本字典(比如 dic),我想在其中添加有关城市的信息,因此数组的示例如下:

lst = ["Belgium", "Flanders", "Antwerp"]

但这可能是:

lst = ["Germany", "Berlin"]

即我要更改字典的键数组的长度是未知的。我可以执行 dic[lst] 之类的操作来直接进入子目录列表吗?

理想情况下,每当 dic[lst] 尝试访问尚未定义的密钥时,它会自动执行此操作。但这不是必需的:我总是可以检查子目录是否存在,并在浏览我的字典之前先初始化所有子目录。

因此我想要一些函数 f,它接受一个字典 dic、一个键数组 lst 和一个值 val。该函数应返回字典 dic,但在对应于 lst 的条目中带有 val。

【问题讨论】:

  • 预期输出是什么?字典是如何组织的?
  • 预期的输出是一个包含该城市信息的字典,如货币、人口等。字典的组织如下:我们为任何国家/地区输入一个条目,然后按“大该国可能的一部分”。每个国家的情况都不一样(诚然:德国 - 柏林是一个糟糕的例子),但例如城市卢森堡将是 dic['Luxembourg']['Luxembourg']

标签: python dictionary


【解决方案1】:

如果您查找字典级联,您可以使用以下插入机制:

def insert_cascade(dic,lst,val):
    for item in lst[:-1]:
        subdic = dic.get(item)
        if subdic is None:
            subdic = {}
            dic[item] = subdic
        dic = subdic
    dic[lst[-1]] = val

现在如果我们构造一个world 字典:

world = {}

我们插入给定的样本输入,我们将生成:

>>> world = {}
>>> insert_cascade(world,["Belgium", "Flanders", "Antwerp"],'this is Antwerp')
>>> world
{'Belgium': {'Flanders': {'Antwerp': 'this is Antwerp'}}}
>>> insert_cascade(world,["Germany", "Berlin"],42)
>>> world
{'Belgium': {'Flanders': {'Antwerp': 'this is Antwerp'}}, 'Germany': {'Berlin': 42}}

如果我们稍后决定添加["Belgium", "Flanders", "Leuven"]["Belgium", "Brussels","Brussels"],我们会得到:

>>> insert_cascade(world,["Belgium", "Flanders", "Leuven"],True)
>>> world
{'Belgium': {'Flanders': {'Leuven': True, 'Antwerp': 'this is Antwerp'}}, 'Germany': {'Berlin': 42}}
>>> insert_cascade(world,["Belgium", "Brussels","Brussels"],object())
>>> world
{'Belgium': {'Brussels': {'Brussels': <object object at 0x7f90f2769080>}, 'Flanders': {'Leuven': True, 'Antwerp': 'this is Antwerp'}}, 'Germany': {'Berlin': 42}}

因此,在这些插入之后,我们的world 包含一个字典,其中包含每个城市的'Belgium''Germany',该对象分配给您通过val

请注意,您可以在此处任意深度地嵌套字典。例如,比利时的结构很复杂。因此,对于某些地区/国家,您可能会决定比其他地区/国家更深地嵌套。

【讨论】:

  • 这并不完全符合我的需要,我需要在我们结束的地方放置一个值,当我运行你的代码时,它只会给我一个空字典。
  • @HolyMonk:你能用问题更新问题吗?连同预期的输出。
  • @HolyMonk:我已经更新了答案。它现在是否符合预期的行为?
  • 当我运行你的代码时,它返回的只是一个空字典,在每个循环中你设置 dic = subdic,但是 subdic = {}?
  • @HolyMonk:这是在if 语句中完成的,因此仅当密钥不存在 时。此外,该函数 not 返回任何内容。更新的是字典(此处为world)。
猜你喜欢
  • 2022-01-25
  • 2019-06-12
  • 1970-01-01
  • 2010-12-23
  • 1970-01-01
  • 1970-01-01
  • 2019-06-29
  • 2015-08-07
  • 2012-03-23
相关资源
最近更新 更多