-2

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
kirbyfan64sos
  • 10,377
  • 6
  • 54
  • 75
  • It looks like you want us to write some code for you. While many users are willing to produce code for a coder in distress, they usually only help when the poster has already tried to solve the problem on their own. A good way to demonstrate this effort is to include the code you've written so far, example input (if there is any), the expected output, and the output you actually get (console output, tracebacks, etc.). The more detail you provide, the more answers you are likely to receive. Check the [FAQ] and [ask]. – Morgan Thrapp Aug 10 '15 at 17:40
  • You have to add the new key and delete the old one – therealprashant Aug 10 '15 at 17:40
  • 4
    Your dictionary is backwards. Fix that, and you'll have an easier time. – TigerhawkT3 Aug 10 '15 at 17:41
  • http://stackoverflow.com/questions/4406501/change-the-key-value-in-python-dictionary – therealprashant Aug 10 '15 at 17:42
  • You defined a regular dictionary but used the tag `ordereddictionary`. Are you using an actual `collections.OrderedDict` object? – Martijn Pieters Aug 10 '15 at 17:42
  • okay I have reordered the dictionary,but the sequence is changing. I want {'N': '3567.234','E': '4567.2345' }but the output comes as this {'E': '4567.2345', 'N': '3567.234'} . – Sai Gautham Aug 10 '15 at 18:04

2 Answers2

1

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'}
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
0

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?

AlanObject
  • 9,613
  • 19
  • 86
  • 142