Effectively change Python dictator key

I want to replace the keys dictwith shorter options so that they can be sent via cable in a compact form. Is there a way to update the key, rather than create a new item in dictand delete the old one?

What am I 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 am not sure about the internal elements dict. However, it seems that something like this update_keycan avoid the need to delete the old key.

+5
source share
4 answers

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

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

, , - , ?

+3

. , , , .

+3

? , , - , , ?

, - ( ):

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

- :

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

, → . / .

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

All Articles