Reverting (key, value) pairs in a dictionary

Skip Montanaro skip at pobox.com
Thu Oct 30 16:45:06 EST 2003


    Shu-Hsien> How do you turn a dictionary of <original_key>:
    Shu-Hsien> <original_value> into <original_value>: <original_key>, when
    Shu-Hsien> there is no duplicate values?

    Shu-Hsien> For instance, I have a dictionary kk:
    Shu-Hsien> kk = {'abc': ['B', 'C', 'D', 'E'], 'def':['G', 'H']}

    Shu-Hsien> and I want a new dictionary newkk which looks like:
    Shu-Hsien> newkk = {'B':'abc', 'C':'abc', 'D':'abc', 'E':'abc', 'G':'def', 'H':'def'}

How about:

    >>> newkk = {}
    >>> for key in kk:
    ...   val = kk[key]
    ...   newkk.update(dict(zip(val, [key]*len(val))))
    ... 
    >>> newkk
    {'C': 'abc', 'B': 'abc', 'E': 'abc', 'D': 'abc', 'G': 'def', 'H': 'def'}

Skip





More information about the Python-list mailing list