After many attempts to create one-liners that will invert key-value pairs, and reverse an OrderedDict, I have this:
from collections import OrderedDict as OD
attributes=OD((('brand','asus'), ('os','linux'), ('processor','i5'), ('memory','4G')))
print(attributes)
reversed_attributes=OD(reversed(list(attributes.items())))
print(reversed_attributes)
inverted_attributes=OD([reversed(item) for item in attributes.items()])
print(inverted_attributes)
''' Prints
OrderedDict([('brand', 'asus'), ('os', 'linux'), ('processor', 'i5'), ('memory', '4G')])
OrderedDict([('memory', '4G'), ('processor', 'i5'), ('os', 'linux'), ('brand', 'asus')])
OrderedDict([('asus', 'brand'), ('linux', 'os'), ('i5', 'processor'), ('4G', 'memory')])
'''
This works, but is it inefficient? By using reversed(list(a.items())) is this creating a lot of overhead, and so is not pythonic? Same for the inverted_attributes.
The point was to avoid for loops and so on, but will this decrease performance as we scale up?
interesting I also came up with other ways.
if you want to reverse you can do this
or a more pythonic approach:
note you don’t need to create
listitems is already a list, and whilereversedis a generatorOrderedDictwill simply iterate through to it generate the new dict.both generating similar timings.
if you want to invert:
or more pythonic:
again both generating similar timings.
you can use the two methods in conjunction to both reverse and invert.
something can generate a lot of overhead and be pythonic on the other hand something can very very efficient and not be very pythonic, the term has being a bit abused, but thats just my opinion
exert from wikipedia:
as for:
This hard to say, without knowing why you are making such transforms, or whether or not their an integral part of your system, fundamentally at a bare minimun they are adding linear time/space overhead which may or may not be good, if the number of entries remains small, then no problem but if at every request, assuming this happening at a web server, your are doing this on a large dicts, this can be quite harsh, and may require a redesign to avoid this.