Tim McNamara
Tim McNamara

Reputation: 18385

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.

Upvotes: 6

Views: 3217

Answers (4)

mcandre
mcandre

Reputation: 24602

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

Upvotes: 3

Jochen Ritzel
Jochen Ritzel

Reputation: 107618

longer = dict(long_key=None)
mapping = dict(long_key='l')
shorter = dict((mapping[k], v) for k,v in longer.iteritems())

Upvotes: 0

viraptor
viraptor

Reputation: 34145

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.

Upvotes: 1

Claudiu
Claudiu

Reputation: 229361

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?

Upvotes: 4

Related Questions