简体   繁体   English

元素组合形成嵌套字典

[英]Combinations of elements to form nested dictionary

I have a dictionary, with integers as key (1 up to n), and values being lists (1 up to m elements).我有一个字典,整数作为键(1 到 n),值是列表(1 到 m 个元素)。 I would like to create a new dictionary, with the primary key being an integer (1 up to each n * m), and the secondary key the original n key with values as strings from the list.我想创建一个新字典,主键是 integer(每个 n * m 为 1),辅助键是原始 n 键,其值为列表中的字符串。

Input:输入:

input = {
        1: ['foo', ...],
        2: ['buz', ...],
        3: ['sam', 'foo', ...],
        4: ['bar', ...],
        5: ['foo', 'bar', ...]
        ...
        }

Where... marks more values being present.哪里... 标志着更多的价值存在。 Values are sometimes the same, sometimes not, and order is not important here even though I used lists.值有时相同,有时不同,即使我使用了列表,这里的顺序也不重要。

Output: for this particular case (if... omitted). Output:对于这种特殊情况(如果...省略)。

output = {
         1: {1: 'foo', 2: 'buz', 3: 'sam', 4: 'bar', 5: 'foo'},
         2: {1: 'foo', 2: 'buz', 3: 'sam', 4: 'bar', 5: 'bar'},
         3: {1: 'foo', 2: 'buz', 3: 'bar', 4: 'bar', 5: 'foo'},
         4: {1: 'foo', 2: 'buz', 3: 'bar', 4: 'bar', 5: 'bar'}
         }

Edit: second example编辑:第二个例子

input = {
        1: ['alice'],
        2: ['tom', 'josh'],
        3: ['mike', 'adam'],
        4: ['kate', 'filip'],
        }

output = {
         1: {1: 'alice', 2: 'tom', 3: 'mike', 4: 'kate'},
         2: {1: 'alice', 2: 'tom', 3: 'mike', 4: 'filip'},
         3: {1: 'alice', 2: 'tom', 3: 'adam', 4: 'kate'},
         4: {1: 'alice', 2: 'tom', 3: 'adam', 4: 'filip'},
         5: {1: 'alice', 2: 'josh', 3: 'mike', 4: 'kate'},
         6: {1: 'alice', 2: 'josh', 3: 'mike', 4: 'filip'},
         7: {1: 'alice', 2: 'josh', 3: 'adam', 4: 'kate'},
         8: {1: 'alice', 2: 'josh', 3: 'adam', 4: 'filip'},
         }

If someone has at least a hint I would very much appreciate it.如果有人至少有一个提示,我将非常感激。 Since I can't find the working solution at all.因为我根本找不到有效的解决方案。

Thanks all in advance提前谢谢大家

You can use itertools.product and a nested dictionary comprehension:您可以使用itertools.product和嵌套字典理解:

from itertools import product
out = {i+1: {j+1: e for j,e in enumerate(x)}
       for i,x in enumerate(product(*data.values()))}

output: output:

{1: {1: 'foo', 2: 'buz', 3: 'sam', 4: 'bar', 5: 'foo'},
 2: {1: 'foo', 2: 'buz', 3: 'sam', 4: 'bar', 5: 'bar'},
 3: {1: 'foo', 2: 'buz', 3: 'foo', 4: 'bar', 5: 'foo'},
 4: {1: 'foo', 2: 'buz', 3: 'foo', 4: 'bar', 5: 'bar'}}

Input:输入:

data = {1: ['foo'], 2: ['buz'], 3: ['sam', 'foo'], 4: ['bar'], 5: ['foo', 'bar']}

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

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