【问题标题】:Reversing logic of a product-country mapping产品-国家映射的反转逻辑
【发布时间】:2023-04-10 03:53:01
【问题描述】:

我有一本字典,可以将 territory_code 映射到可用的 productIds

items = {'US': set(123, 948, 200), 'AG': set(132, 123), 'AZ': set(123)}

我想反转映射,以便它为我提供项目并将它们映射到区域。它应该给我:

{123: set('US', 'AZ', 'AG'), 948: set('US'), 200: set('US'), 132: set('AG')}

我将如何进行这种反转?

【问题讨论】:

    标签: python dictionary set


    【解决方案1】:

    您可以尝试蛮力方式。

    逻辑 - 为旧字典中的每个值在新字典中创建一个新键并将旧键添加为新值

    >>> newdic = {}
    >>> for k,v in items.items():
    ...     for i in v:
    ...         if i not in newdic:
    ...               newdic[i] = set()
    ...         newdic[i].add(k)
    ... 
    >>> newdic 
    {200: set(['US']), 948: set(['US']), 123: set(['AZ', 'US', 'AG']), 132: set(['AG'])}
    

    没有 REPL 箭头的裸代码

    for k,v in items.items():
        for i in v:
            if i not in newdic:
                  newdic[i] = set()
            newdic[i].add(k)
    

    这里有一个小提示。如果允许导入,则可以使用 defaultdict from collections

    >>> from collections import defaultdict
    >>> newdic = defaultdict(set)
    >>> for k,v in items.items():
    ...     for i in v:
    ...         newdic[i].add(k)
    ... 
    >>> dict(newdic)
    {200: set(['US']), 132: set(['AG']), 123: set(['AZ', 'US', 'AG']), 948: set(['US'])}
    

    这样可以避免在两者之间使用if 子句。

    【讨论】:

      【解决方案2】:

      使用多行方法更具可读性,但这里只是为了好玩而使用单行:

      >>> items = {'US': {123, 948, 200}, 'AG': {132, 123}, 'AZ': {123}}
      >>> {value: {country for country in items if value in items[country]} for value in set.union(*items.values())}
      {200: set(['US']), 132: set(['AG']), 123: set(['AZ', 'US', 'AG']), 948: set(['US'])}
      

      【讨论】:

        【解决方案3】:
        rev_map = {}
        for code, product_ids in items.items():
            for product_id in product_ids:
                rev_map.setdefault(product_id, set()).add(code)
        

        【讨论】:

          猜你喜欢
          • 2016-12-17
          • 1970-01-01
          • 2014-09-15
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-04-05
          • 1970-01-01
          • 2016-05-16
          相关资源
          最近更新 更多