Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Efficiently change a key of a Python dict

I'm looking to replace the keys of a dict to shorter variants so that it can be sent across the wire in a compact form. Is there a way to updating a key, rather than creating a new item in in the dict and deleting the old?

What I'm doing now:

>>> a = dict(long_key=None)
>>> a['l'] = a['long_key']
>>> del a['long_key']

What I would like to do is something like this:

>>> a = dict(long_key=None)
>>> a.update_key('long_key', 'l')

I'm unsure of dict's internals. However, it seems that something like update_key might be able to avoid needing to delete the old key.

like image 783
Tim McNamara Avatar asked Aug 20 '11 00:08

Tim McNamara


3 Answers

A more elegant solution might be to create a new dictionary... essentially make a slightly different shallow copy:

a_send = dict((k[0], v) for k,v in a.items())

That will certainly be less space-efficient, though - are you looking for space efficiency, time efficiency, or code elegance?

like image 90
Claudiu Avatar answered Sep 18 '22 12:09

Claudiu


That's premature optimization. If you really want to save bandwidth, do it by either compressing the data normally or use simpler data structures.

like image 25
mcandre Avatar answered Sep 22 '22 12:09

mcandre


How many times do you need to send it? Maybe instead of changing anything, you can just process the keys as you go?

Instead of doing something like (guessing pseudo-code):

short_dict = shorten_keys(long_dict)
for k,v in short_dict:
    send_over(k,v)

do something like:

for k,v in long_dict:
    send_over(shorten(k),v)

If you have to send it many times, you can also create a map of long -> short keys and use it while sending. Wasting space / time to create copies might not be the best solution.

like image 32
viraptor Avatar answered Sep 18 '22 12:09

viraptor