如何从嵌套字典中查找列表的组合 [英] How to find combinations of lists from nested dictionaries

查看:32
本文介绍了如何从嵌套字典中查找列表的组合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑嵌套字典:

d1 = {'key': {'r1': [1,2,3],
              'r2': [5,6]} }

我想从上面的字典中提取字典列表,该字典采用嵌套字典列表项的所有组合.例如,对于上面的字典,我想要这样做:

I want to extract a list of dictionaries from the above dict which takes all combinations of the nested dictionary's list items. For example, for the above dict, I would want this:

ans = [ {'root': 'key', 'r1': 1, 'r2':5},
        {'root': 'key', 'r1': 1, 'r2':6},
        {'root': 'key', 'r1': 2, 'r2':5},
        {'root': 'key', 'r1': 2, 'r2':6},
        {'root': 'key', 'r1': 3, 'r2':5},
        {'root': 'key', 'r1': 3, 'r2':6}
      ]

对于上面的示例,我可以手动执行此操作,但是问题是d1中除"root"以外的键数可以是任何变量数,并且我的答案会更改,例如,考虑:

I can do this manually for the above example but the issue is that the number of keys apart from 'root' in d1 could be any variable number and my answer would change, for eg, consider:,

d2 = {'key': {'r1': [1,2,3],
              'r2': [5,6],
              'r3': [7,8]}
     }

现在答案将如下所示:

ans = [ {'root': 'key', 'r1': 1, 'r2':5, 'r3':7},
        {'root': 'key', 'r1': 1, 'r2':6, 'r3':8},
        {'root': 'key', 'r1': 2, 'r2':5, 'r3':7},
        {'root': 'key', 'r1': 2, 'r2':6 ,'r3':8},
        .
        .(total 12 combinations)
      ]

我可以使用itertools.product在可变数量的列表中查找项目组合,如下所示:

I can use the itertools.product to find combinations of items in variable number of lists as following:

from itertools import product
list(product(d1['key']['r1'], d1['key']['r2']))

返回:

[(1, 5), (1, 6), (2, 5), (2, 6), (3, 5), (3, 6)]

但是如何将对应的密钥添加到这些项中的每一个中,又如何动态地执行呢?

But how can I add the corresponding keys to each of these items and how can I do this dynamically?

推荐答案

只要"root"不变,就可以分别使用 itertools.product zip 带有字典键的产品:

As long as the "root" is unchanging, you can use itertools.product and zip each product with the dictionary keys:

>>> from itertools import product
>>> combinations = product(*d2['key'].values())
>>> [{'root': 'key', **dict(zip(d2['key'].keys(), c))} for c in combinations]   

[{'r1': 1, 'r2': 5, 'r3': 7, 'root': 'key'},
 {'r1': 1, 'r2': 5, 'r3': 8, 'root': 'key'},
 {'r1': 1, 'r2': 6, 'r3': 7, 'root': 'key'},
 {'r1': 1, 'r2': 6, 'r3': 8, 'root': 'key'},
 ...

非常感谢, dict.keys() dict.values()会以相应的顺序返回键和值,而不管您的python版本如何,这可以通过以下方式保证规格.

Thankfully, dict.keys() and dict.values() return the keys and values in their corresponding order, regardless of your python version, this is guaranteed by the spec.

这篇关于如何从嵌套字典中查找列表的组合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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