在Python语言中组合任意长度的嵌套词典 [英] Combination of nested dictionaries with arbitrary lengths in python

查看:27
本文介绍了在Python语言中组合任意长度的嵌套词典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一个函数,该函数将接受嵌套字典,并生成值的组合/乘积。

我的查询与此处指定的问题类似,但我似乎无法调整答案以满足我的需求: Cartesian product of nested dictionaries of lists

我希望有这样的输入:

d = {
  "country": [1, 2],
  "health_state": [
    {"healthy": [1]},
    {"breast cancer": {"stage": [1, 2]}}
  ]
}

生成如下输出:

[
{{"country":1},{"health state":{"healthy":1}}},
{{"country":2},{"health state":{"healthy":1}}},
{{"country":1},{"health state":{"breast cancer":{"stage":1}}}},
{{"country":1},{"health state":{"breast cancer":{"stage":2}}}},
{{"country":2},{"health state":{"breast cancer":{"stage":1}}}},
{{"country":2},{"health state":{"breast cancer":{"stage":2}}}}
]

在本例中,输出是一个人可以占据的"状态"列表

  • 列表(输入)的任意两个元素不能在返回列表(输出)的同一元素中,例如某个人不能同时在国家1和国家2
  • 字典(输入)中的所有键应该在列表(输出)的同一元素中返回,例如某人在国家/地区1并且也处于Health_State。如果健康状态为‘乳腺癌’,则他们也处于阶段1或阶段2

我可以设想一种需要大量for循环的解决方案,检查元素是字典、列表还是两者都不是,但这似乎效率很低,特别是对于深度嵌套的字典。我怀疑有一个更好的解决方案,使用itertools.product和递归?

推荐答案

您可以对itertools.product使用递归:

import itertools as it
d = {'country': [1, 2], 'health_state': [{'healthy': [1]}, {'breast cancer': {'stage': [1, 2]}}]}
def c_prod(d):
  if isinstance(d, list):
     for i in d:
        yield from ([i] if not isinstance(i, (dict, list)) else c_prod(i))
  else:
     for i in it.product(*map(c_prod, d.values())):
        yield dict(zip(d.keys(), i))

print(list(c_prod(d)))

输出:

[{'country': 1, 'health_state': {'healthy': 1}}, 
 {'country': 1, 'health_state': {'breast cancer': {'stage': 1}}}, 
 {'country': 1, 'health_state': {'breast cancer': {'stage': 2}}}, 
 {'country': 2, 'health_state': {'healthy': 1}}, 
 {'country': 2, 'health_state': {'breast cancer': {'stage': 1}}}, 
 {'country': 2, 'health_state': {'breast cancer': {'stage': 2}}}]

以上代码的输出生成一个词典列表,但您需要的输出反映了一个词典列表(list[list[dict]]),因此可以进行最终转换:

r = [[{j:k} for j, k in i.items()] for i in c_prod(d)]

输出:

[[{'country': 1}, {'health_state': {'healthy': 1}}], [{'country': 1}, {'health_state': {'breast cancer': {'stage': 1}}}], [{'country': 1}, {'health_state': {'breast cancer': {'stage': 2}}}], [{'country': 2}, {'health_state': {'healthy': 1}}], [{'country': 2}, {'health_state': {'breast cancer': {'stage': 1}}}], [{'country': 2}, {'health_state': {'breast cancer': {'stage': 2}}}]]

这篇关于在Python语言中组合任意长度的嵌套词典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆