reading diveintopython3 came upon this and can’t deconstruction into smaller bits i understand.
>>> a_dict = {'a': 1, 'b': 2, 'c': 3}
>>> {value:key for key, value in a_dict.items()}
>>> {1: 'a', 2: 'b', 3: 'c'}
a_dict.items() creates a list. But value in a_dict.items() doesn’t make sense to me as value isn’t defined…
whats going on here?
a_dict.keys()is a list of keys in your dictionarya_dict.values()is a list of values in your dictionarya_dict.items()is a list of (key, value) pairs{value:key for key, value in a_dict.items()}is a dict() comprehension which takesa_dictand switches its keys with its values, returning a new data structure as the result. If you look closely you can see that in the result part we havevalue:keybut in the iteration part we havekey, value— they switch! Very tricky, very pythonic.If there are no duplicate values in
a_dict, this will result the inverse of the original dictionary. If there are duplicates, since all keys in the new dict must be unique, only one of the mappings of each of the duplicated values will survive.Here’s a simpler example of a dict() comprehension if you’re having difficulty understanding how they work; type it in to your interactive editor and mess around with it!