我正在尝试使用下面的代码创建一个字典:
def func(inp):
return (dict(zip(inp.keys(), values)) for values in product(*inp.values()))
x ={'Key1': ['111', '42343'], 'key2': ['TEST', 'TESTTT123'], 'Key3': ['Cell Phone', 'e-Mail'], 'Key5': ['32142341', 'test@email.com']}
func(x)
但是它给了我一个笛卡尔积
{'Key1': '111', 'Key2': 'TEST', 'Key3': 'Cell Phone', 'Key4': '32142341'}
{'Key1': '111', 'Key2': 'TEST', 'Key3': 'Cell Phone', 'Key4': 'test@email.com'}
{'Key1': '111', 'Key2': 'TEST', 'Key3': 'e-Mail', 'Key4': '32142341'}
{'Key1': '111', 'Key2': 'TEST', 'Key3': 'e-Mail', 'Key4': 'test@email.com'}
{'Key1': '111', 'Key2': 'TESTTT123', 'Key3': 'Cell Phone', 'Key4': '32142341'}
{'Key1': '111', 'Key2': 'TESTTT123', 'Key3': 'Cell Phone', 'Key4': 'test@email.com'}
{'Key1': '111', 'Key2': 'TESTTT123', 'Key3': 'e-Mail', 'Key4': '32142341'}
{'Key1': '111', 'Key2': 'TESTTT123', 'Key3': 'e-Mail', 'Key4': 'test@email.com'}
{'Key1': '42343', 'Key2': 'TEST', 'Key3': 'Cell Phone', 'Key4': '32142341'}
{'Key1': '42343', 'Key2': 'TEST', 'Key3': 'Cell Phone', 'Key4': 'test@email.com'}
{'Key1': '42343', 'Key2': 'TEST', 'Key3': 'e-Mail', 'Key4': '32142341'}
{'Key1': '42343', 'Key2': 'TEST', 'Key3': 'e-Mail', 'Key4': 'test@email.com'}
{'Key1': '42343', 'Key2': 'TESTTT123', 'Key3': 'Cell Phone', 'Key4': '32142341'}
{'Key1': '42343', 'Key2': 'TESTTT123', 'Key3': 'Cell Phone', 'Key4': 'test@email.com'}
{'Key1': '42343', 'Key2': 'TESTTT123', 'Key3': 'e-Mail', 'Key4': '32142341'}
{'Key1': '42343', 'Key2': 'TESTTT123', 'Key3': 'e-Mail', 'Key4': 'test@email.com'}
但是输出要求是:
{'Key1': '111', 'Key2': 'TEST', 'Key3': 'Cell Phone', 'Key4': '32142341'}
{'Key1': '42343', 'Key2': 'TESTTT123', 'Key3': 'e-Mail', 'Key4': 'test@email.com'}
如何避免笛卡尔积?
使用range
循环遍历列表的长度,并使用字典推导式构建单个字典,每次选择列表的i
第th元素:
def func(inp):
return ({k: v[i] for k, v in inp.items()} for i in range(len(list(inp.values())[0])))
x = {'Key1': ['111', '42343'], 'key2': ['TEST', 'TESTTT123'], 'Key3': ['Cell Phone', 'e-Mail'], 'Key4': ['32142341', 'test@email.com']}
res = func(x)
for r in res:
print(r)
输出:
{'Key1': '111', 'Key2': 'TEST', 'Key3': 'Cell Phone', 'Key4': '32142341'}
{'Key1': '42343', 'Key2': 'TESTTT123', 'Key3': 'e-Mail', 'Key4': 'test@email.com'}
使用第一个键/值对的列表长度,并假设所有列表的长度相等。
您的解决方案非常接近,但不必要地调用笛卡尔积函数。您可以直接压缩输入字典的值,这样您就可以通过使用输入字典的键压缩它们来迭代创建子字典:
def func(inp):
return (dict(zip(inp, values)) for values in zip(*inp.values()))