JAM JAM - 3 months ago 5
Python Question

How to update keys in dictionary?

I have a

{}
with a
string -> list
relationship, like:

'Something.Default.' : ['a=initiator', 'b=00:00:00']
'Something.Session.' : ['b=acceptor', 'c=7039']


I'd like to change keys to drop the last
.
'Something.Default.'
should become
'Something.Default'
.

This is obviously wrong, but it illustrates what I am looking for

for key in my_dictionary:
key = key[:-1]


How can I iterate over each key and change it?

Answer

You should not change a mutable object such as a list or dictionary while iterating over its contents, so you are best of creating a new dictionary modifying the relevant keys where necessary. This uses a ternary to truncate the key by one character if it ends in a period ('.'), otherwise use the original key.

my_dictionary = {key[:-1] if key[-1] == '.' else key: value
                 for key, value in my_dictionary.iteritems()}  # Python 2

The new dictionary is reassigned to the old variable name my_dictionary.

Comments