颠倒产品国家映射的逻辑

时间:2015-06-09 19:36:04

标签: python dictionary set

我有一本字典,可以将class GameObject { // separate variable for the transition component private Transition transition; private List<Component> components; public T GetComponent<T>() where T : Component { // if a transition is requestet just return it if(typeof(T) == typeof(Transition)) { return transition; } // else: search the requested component in the list foreach(Component comp in components) { if(comp is T) return (T)comp; } // return null or throw exception when not found return null; } public void RemoveComponent<T>() where T : Component { if(typeof(T) != typeof(Transition)) { // only remove the componenent if it's not a Transition component Component tmp; foreach(Component comp in components) { if(comp is T) tmp = comp; break; } components.Remove(tmp); } } } 映射到territory_code可用的字词:

productIds

我想反转映射,以便它给我项目并将它们映射到领土。它应该给我:

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

我该怎么做这个倒车?

3 个答案:

答案 0 :(得分:3)

你可以尝试蛮力的方式。

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

>>> 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)

这里有一个小小的说明。如果您被允许导入,则可以使用collections

中的defaultdict
>>> 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子句。

答案 1 :(得分:3)

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

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

答案 2 :(得分:2)

rev_map = {}
for code, product_ids in items.items():
    for product_id in product_ids:
        rev_map.setdefault(product_id, set()).add(code)