6

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.

Tim McNamara
  • 18,019
  • 4
  • 52
  • 83
  • are you looking for space efficiency, time efficiency, or code elegance? – Claudiu Aug 20 '11 at 00:23
  • 7
    Compressing your transport is probably a saner solution than obfuscating your data. – Glenn Maynard Aug 20 '11 at 00:44
  • 2
    Just to respond to criticisms about the approach- I asked the question because I'm interested in learning about how the Python `dict` works. These tiny snippets don't represent the whole of what I'm doing, they just serve to demonstrate my intentions to make the question clearer. Downvoting a Q on the basis that you don't like its subject matter is a bit petty. Questions should be downvoted because they're unclear or vague. – Tim McNamara Aug 20 '11 at 02:10
  • @Claudiu- For this part of the code, time efficiency. – Tim McNamara Aug 20 '11 at 02:12
  • 1
    For more info about the `dict` implementation in CPython see some of the references here: http://stackoverflow.com/questions/327311/how-are-pythons-built-in-dictionaries-implemented – Ned Deily Aug 20 '11 at 04:52

4 Answers4

4

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?

Claudiu
  • 224,032
  • 165
  • 485
  • 680
3

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

mcandre
  • 22,868
  • 20
  • 88
  • 147
1

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.

viraptor
  • 33,322
  • 10
  • 107
  • 191
0
longer = dict(long_key=None)
mapping = dict(long_key='l')
shorter = dict((mapping[k], v) for k,v in longer.iteritems())
Jochen Ritzel
  • 104,512
  • 31
  • 200
  • 194