1

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?

Morgan Thrapp
  • 9,748
  • 3
  • 46
  • 67
James Raitsev
  • 92,517
  • 154
  • 335
  • 470

4 Answers4

4

Just create a new dictionary with the modifications.

orig_dict = {'foox': 'bar', 'bazx': 'bat'}
new_dict = {key[:-1]: value for key, value in orig_dict.items()}
Morgan Thrapp
  • 9,748
  • 3
  • 46
  • 67
2

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.

Alexander
  • 105,104
  • 32
  • 201
  • 196
1

get each key , make new key with last . removed, then transfer data and delete that dict.

for info in dict:
  if info[-1]=='.':
    dict[info[:-1]] = dict[info]
    del dict[info]
harshil9968
  • 3,254
  • 1
  • 16
  • 26
0

Morgan Thrapp's answer was bang on. but here's a little modification

orig_dict = {key[:-1]: value for key, value in orig_dict.items()}

You don't need to create a new dict object. Just a minor clean up job.

Ashish Padakannaya
  • 463
  • 2
  • 7
  • 17