dictionary - Python reverse / inverse a mapping (but with multiple values for each key) -


this variation on question, not duplicate:

python reverse / invert mapping

given dictionary so:

mydict= { 'a': ['b', 'c'], 'd': ['e', 'f'] }

how can 1 invert dict get:

inv_mydict = { 'b':'a', 'c':'a', 'e':'d', 'f':'d' }

note values span uniquely under each key.

note: had syntax map = ... , dict = ... reminder not use map , dict built-in functions, see excellent comments , answers below :)

tl;dr

use dictionary comprehension, this

>>> my_map = { 'a': ['b', 'c'], 'd': ['e', 'f'] } >>> {value: key key in my_map value in my_map[key]} {'c': 'a', 'f': 'd', 'b': 'a', 'e': 'd'} 

the above seen dictionary comprehension functionally equivalent following looping structure populates empty dictionary

>>> inv_map = {} >>> key in my_map: ...     value in my_map[key]: ...         inv_map[value] = key ...  >>> inv_map {'c': 'a', 'f': 'd', 'b': 'a', 'e': 'd'} 

note: using map shadows built-in map function. so, don't use variable name unless know doing.


other similar ways same

python 3.x

you can use dict.items, this

>>> {value: key key, values in my_map.items() value in values} {'c': 'a', 'f': 'd', 'b': 'a', 'e': 'd'} 

we use items() method here, create view object dictionary give key value pairs on iteration. iterate on , construct new dictionary inverse mapping.

python 2.x

you can use dict.iteritems this

>>> {value: key key, values in my_map.iteritems() value in values} {'c': 'a', 'b': 'a', 'e': 'd', 'f': 'd'} 

we don't prefer items() method in 2.x, because return list of key-value pairs. don't want construct list iterate , construct new dictionary. why prefer iteritems(), returns iterator object gives key value pair on iteration.

note: actual equivalent of python 3.x's items python 2.x's viewitems method, returns view object. read more view object in official documentation, here.


iter* vs view* methods in python 2.x

the main difference between iter* functions , view* functions in python 2.x that, view objects reflect current state of dictionary. example,

>>> d = {1: 2} >>> iter_items = d.iteritems() >>> view_items = d.viewitems() 

now add new element dictionary

>>> d[2] = 3 

if try check if (2, 3) (key-value pair) in iter_items, throw error

>>> (2, 3) in iter_items traceback (most recent call last):   file "<input>", line 1, in <module> runtimeerror: dictionary changed size during iteration 

but view object reflect current state of dictionary. so, work fine

>>> (2, 3) in view_items true 

Comments

Popular posts from this blog

css - SVG using textPath a symbol not rendering in Firefox -

Java 8 + Maven Javadoc plugin: Error fetching URL -

order - Notification for user in user account opencart -