Python Forum
Change the key value in dictionary
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Change the key value in dictionary
#2
The thing on the left is usually called a "key" and the thing on right is a "value".

There's no way to really "modify" a key. Instead you would create the new key and delete the old one.

But odder to me is that your keys are not all the same type. Most are tuples and some are strings. The way to "add i to it" depends on the type. If it was always a tuple, you could do something like:

import pprint
d = {('i', 'i'): (0.4958635668040591+0.033985852749267645j),
 ('i', 'x'): (-3.713537562982453e-06-2.578284945296621e-07j),
 ('i', 'y'): (-2.078134606106431e-06-1.5092272785217425e-07j),
 ('i', 'z'): (0.0030247632238068057+0.00019935846367565656j),
 }

d = {(*k, "i"): v for k,v in d.items()}

pprint.pprint(d)
Output:
{('i', 'i', 'i'): (0.4958635668040591+0.033985852749267645j), ('i', 'x', 'i'): (-3.713537562982453e-06-2.578284945296621e-07j), ('i', 'y', 'i'): (-2.078134606106431e-06-1.5092272785217425e-07j), ('i', 'z', 'i'): (0.0030247632238068057+0.00019935846367565656j)}
But if some of your keys aren't tuple, you'd have to do more work. Probably loop over the original dict, then create the necessary key/value in a new one based on whether the first key is a tuple or a string.
quest likes this post
Reply


Messages In This Thread
Change the key value in dictionary - by quest - Mar-25-2022, 01:42 AM
RE: Change the key value in dictionary - by bowlofred - Mar-25-2022, 02:14 AM
RE: Change the key value in dictionary - by quest - Mar-25-2022, 04:47 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  How to change value in a nested dictionary? nzcan 2 5,857 Sep-23-2019, 04:09 PM
Last Post: nzcan

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020