简体   繁体   English

使用嵌套列表生成 python dict 的排列

[英]Generate permutations of python dict with nested lists

I have a python dictionary which includes some nested lists and might look as follows:我有一个 python 字典,其中包括一些嵌套列表,可能如下所示:

Dict = {
"a": [0.1, 20],
"b": 300,
"c": ["sun", "moon"],
"d": "water",
}

I am now trying to generate all possible unique permutations of this dictionary where each key only has one entry (ie no nested lists anymore).我现在正在尝试生成该字典的所有可能的唯一排列,其中每个键只有一个条目(即不再有嵌套列表)。 The desired dictionaries would look like these:所需的字典如下所示:

Dict1 = {
"a": 0.1,
"b": 300,
"c": "sun",
"d": "water",
}

Dict2 = {
"a": 0.1,
"b": 300,
"c": "moon",
"d": "water",
}

Dict3 = {
"a": 20,
"b": 300,
"c": "sun",
"d": "water",
}

Dict4 = {
"a": 20,
"b": 300,
"c": "moon",
"d": "water",
}

After looking at comparable problems I have tried my luck with itertools but have not succeeded thus far.在查看了类似的问题后,我尝试了 itertools 的运气,但到目前为止还没有成功。 I am rather new to pyhton and am also not sure if dictionaries are even the most appropriate datastructure for this problem, so any advice will me much appreciated.我对 pyhton 很陌生,也不确定字典是否是解决这个问题的最合适的数据结构,所以我将不胜感激任何建议。

import itertools 
keys, values = zip(*Dict.items()) 
results = [dict(zip(keys, v)) for v in itertools.product(values)] 

You can iterate over the mappings that you have, and您可以迭代您拥有的映射,并且

  • if the value is a list: you combine existing dicts with all values (a product)如果该值是一个列表:您将现有的字典与所有值(一个产品)结合起来
  • if the value is is single, you just add it to each dict如果值是单一的,你只需将它添加到每个字典
def expand_dd(dd):
    result = [{}]
    for key, value in dd.items():
        if isinstance(value, list):
            result = [{**d, key: v} for d in result for v in value]
        else:
            result = [{**d, key: value} for d in result]
    return result



dd = {"a": [0.1, 20], "b": 300, "c": ["sun", "moon"], "d": "water"}
e = expand_dd(dd)
print(e)
# [{'a': 0.1, 'b': 300, 'c': 'sun', 'd': 'water'},
#  {'a': 0.1, 'b': 300, 'c': 'moon', 'd': 'water'},
#  {'a': 20, 'b': 300, 'c': 'sun', 'd': 'water'},
#  {'a': 20, 'b': 300, 'c': 'moon', 'd': 'water'}]

It is better to put the resulting dicts in a list rather than assigning them to unrelated variables.最好将结果字典放在一个列表中,而不是将它们分配给不相关的变量。

We can use itertools.product to create the values, but we have to take care before and put the 'isolated values' like your integer and your string in a list of its own.我们可以使用itertools.product来创建值,但我们必须先小心,并将像您的 integer 和您的字符串这样的“隔离值”放在它自己的列表中。 We leave the lists and tuples as they are, you can adjust the rule to your own needs.我们将列表和元组保持原样,您可以根据自己的需要调整规则。

Then, we can create the list of dicts by reassembling the keys with the values.然后,我们可以通过将键与值重新组合来创建字典列表。

from itertools import product

data = {
"a": [0.1, 20],
"b": 300,
"c": ["sun", "moon"],
"d": "water",
}

product_values = product(*[v if isinstance(v, (list, tuple)) else [v] for v in data.values()])
out = [dict(zip(data.keys(), values)) for values in product_values]
print(out)
# [{'a': 0.1, 'b': 300, 'c': 'sun', 'd': 'water'}, 
#  {'a': 0.1, 'b': 300, 'c': 'moon', 'd': 'water'},
#  {'a': 20, 'b': 300, 'c': 'sun', 'd': 'water'}, 
#  {'a': 20, 'b': 300, 'c': 'moon', 'd': 'water'}]

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

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