ASPN ActiveState Programmer Network  
ActiveState, a division of Sophos
/ Home / Perl / PHP / Python / Tcl / XSLT /
/ Safari / My ASPN /
Cookbooks | Documentation | Mailing Lists | Modules | News Feeds | Products | User Groups
Submit Recipe
My Recipes

All Recipes
All Cookbooks


View by Category

Title: Expanded dictionary inversion
Submitter: Jonathan Knoll (other recipes)
Last Updated: 2006/07/11
Version no: 1.0
Category: Shortcuts

 

4 stars 2 vote(s)


Description:

Invert different types of dictionaries with mixed data types as values.

Source: Text Source

def invert1(d):
    dd = {}
    for k, v in d.items():
        if not isinstance(v, (tuple, list)): v = [v]
        dd.update( [(vv, dd.setdefault(vv, []) + [k]) for vv in v] )
    return dd


def invert2(d):
    dd = {}
    for k, v in d.items():
        if not isinstance(v, (tuple, list)): v = [v]
        [dd.setdefault(vv, []).append(k) for vv in v]
    return dd

Discussion:

I just wanted to add a few more possibilities to the inverters in these recipes:

   http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/252143
   http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/415100

The difference between these two can be seen using {'A': [1, 1]}:
   invert1({'A': [1, 1]}) --> {1: ['A']}
   invert2({'A': [1, 1]}) --> {1: ['A', 'A']}

You can try it out with these as well:
   {'A': (1,), 'C': (3, 3), 'B': (2, 4)}
   {'A': [3, 2, 1], 'C': [3, 2], 'B': [1, 4]}
   {'A': 2, 'C': 4, 'B': 5, 'D': 5}
   {'A': 2, 'C': 4, 'B': 5, 'D': [5, 3]}
   {'A': [1, 2, 3], 'B': 4}



Add comment

No comments.



Highest rated recipes:

1. A simple XML-RPC server

2. Web service accessible ...

3. Wrapping template engine ...

4. Assignment in expression

5. SOLVING THE METACLASS ...

6. Povray for python

7. Calling Windows API ...

8. Generic filter logic ...

9. Function Decorators by ...

10. MS SQL Server log monitor




Privacy Policy | Email Opt-out | Feedback | Syndication
© 2006 ActiveState Software Inc. All rights reserved.