开发者

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?

Wh开发者_运维知识库at 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.


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?


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


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.


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜