简体   繁体   English

Python:在嵌套字典中循环并组合值

[英]Python: Looping over and combining values in nested dictionaries

I am creating a nested dictionary that describes several cases ('1ql' and '2ql'), each with a different number of variations ('var0', 'var1', ...). 我正在创建一个嵌套的字典,该字典描述了几种情况(“ 1ql”和“ 2ql”),每种情况都有不同的变体数量(“ var0”,“ var1”等)。 I use dict comprehension in the following manner: 我通过以下方式使用dict理解:

from numpy import random as rnd

QLS = {
    key: {
        idx: rad
        for idx, rad in enumerate(['var{}'.format(i) for i in range(rnd.randint(1, 4))])
        }
    for key in ['1ql', '2ql']
    }

This works great, but I have been struggling with the how to handle the dictionary for saving to file(s). 这很好用,但是我一直在努力处理如何将字典保存到文件中。 I would like to iterate over each variation of '1ql', and then iterate simultaneously over each iteration of '2ql'. 我想遍历“ 1ql”的每个变体,然后同时遍历“ 2ql”的每个迭代。 This can easily be accomplished like this: 可以很容易地像这样完成:

for key1, val1 in QLS['1ql'].items():
    for key2, val2 in QLS['2ql'].items():
        print('1ql: {}, 2ql: {}'.format(val1, val2))

which, for 2 variations of '1ql' and 3 variation '2ql', produces 6 total permutations: 对于“ 1ql”的2个变体和“ 2ql”的3个变体,将产生6个总置换:

1ql: var0, 2ql: var0
1ql: var0, 2ql: var1
1ql: var0, 2ql: var2
1ql: var1, 2ql: var0
1ql: var1, 2ql: var1
1ql: var1, 2ql: var2

However, I would like to get this automatically for any number of cases, for any number of variations per case, without having to specify these by hand. 但是,我想自动针对任意数量的案例,针对每种案例的任意数量的变体获取此信息,而无需手动指定。 I have tried different iteration schemes and even by inverting the inner and outer keys, but to no avail. 我尝试了不同的迭代方案,甚至通过反转内部和外部键,但都无济于事。

I would really like the to learn the most pythonic way to accomplish this. 我真的很想学习实现这一点的最pythonic方法。 Thanks! 谢谢!

First, transform the data to remove the parts we don't need: 首先,转换数据以删除我们不需要的部分:

x = [[(case, var) for var in QLS[case].values()] for case in QLS.keys()]

Now x is something like: 现在x是这样的:

[[('1ql', 'var0'), ('1ql', 'var1'), ('1ql', 'var2')],
 [('2ql', 'var0'), ('2ql', 'var1'), ('2ql', 'var2')]]

Finally, use itertools.product() to get the result: 最后,使用itertools.product()获得结果:

list(itertools.product(*x))

Probably in your real code you'll iterate over the results and use print() on each one to get the format you need, but wrapping with list() as above gives you an idea: 可能在您的真实代码中,您将遍历结果并在每个代码上使用print()获得所需的格式,但是如上所述用list()包装可以使您有一个主意:

[(('1ql', 'var0'), ('2ql', 'var0')),
 (('1ql', 'var0'), ('2ql', 'var1')),
 (('1ql', 'var0'), ('2ql', 'var2')),
 (('1ql', 'var1'), ('2ql', 'var0')),
 (('1ql', 'var1'), ('2ql', 'var1')),
 (('1ql', 'var1'), ('2ql', 'var2')),
 (('1ql', 'var2'), ('2ql', 'var0')),
 (('1ql', 'var2'), ('2ql', 'var1')),
 (('1ql', 'var2'), ('2ql', 'var2'))]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM