My dictionary is
data={'3567.234' : 'N' , '4567.2345' : 'E'}
based on the value for a key ,I want to change the key.
like this:
for key in data:
if data[key] == 'E':
key = -1 * key
My dictionary is
data={'3567.234' : 'N' , '4567.2345' : 'E'}
based on the value for a key ,I want to change the key.
like this:
for key in data:
if data[key] == 'E':
key = -1 * key
You may want to consider inverting your dictionary:
data = {'N': '3567.234', 'E': '4567.2345'}
and you'll have an easier time of operating on the values.
If you must have the directions as values and coordinates as keys, then you could just re-create the dictionary with a dict comprehension:
data = {key[1:] if key.startswith('-') else '-' + key: value for key, value in data.items()}
I used string manipulation here; your keys are strings after all, not numerical values. It simply prepends the key with '-'
if none is there, otherwise removes the first character.
Demo:
>>> data = {'3567.234': 'N', '4567.2345': 'E'}
>>> {key[1:] if key.startswith('-') else '-' + key: value for key, value in data.items()}
{'-4567.2345': 'E', '-3567.234': 'N'}
It looks like you have a misconception. You don't need to change the value of a key you need to create a new key that references the same data value.
data={'3567.234' : 'N' , '4567.2345' : 'E'}
data['xyz'] = data['3567.234']
data.pop('3567.234', None)
Is that what you wanted?