【问题标题】:Need to create a dictionary from multiple values需要从多个值创建字典
【发布时间】:2021-05-01 05:04:59
【问题描述】:

我正在尝试使用以下代码创建字典:

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'}

任何帮助如何避免笛卡尔积?

【问题讨论】:

    标签: python-3.x python-2.7 dictionary


    【解决方案1】:

    只需使用range 遍历列表的长度并使用dictionary comprehension 来构造单独的字典,每次选择列表的ith 元素:

    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'}
    

    这使用第一个键/值对的列表长度,并假设所有列表的长度相同。

    【讨论】:

      【解决方案2】:

      您的解决方案非常接近,但不必要地调用笛卡尔积函数。您可以改为直接压缩输入字典的值,以便您可以通过使用输入字典的键压缩它们来遍历它们以创建子字典:

      def func(inp):
          return (dict(zip(inp, values)) for values in zip(*inp.values()))
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-03-14
        • 2023-03-25
        • 2021-12-07
        • 2022-06-27
        • 2018-05-10
        • 1970-01-01
        • 2014-04-16
        • 2021-12-04
        相关资源
        最近更新 更多