9

I want to do something like this:

my_dict = {"key": "value", "key1": "value1", "key2": my_dict["key"]}

and have the result be:

{"key": "value", "key1": "value1", "key2": "value"}

Currently getting unresolved reference unless I declare the dict() prior. Otherwise I get a key error.

Nicolas
  • 331
  • 4
  • 13
  • `my_dict = {"key": "value", "key1": "value1"}; my_dict["key2"] = my_dict["key"]` bam – Ry- Feb 17 '17 at 01:38
  • 2
    Well, your dict is not initialized, you cannot reference something that doesn't yet exist. You can use `lambda` to dynamically call your keys if you want to create a self-referencing dictionary. – zwer Feb 17 '17 at 01:39
  • 1
    @Nicolas, the problem is that assignment statements are evaluated right to left, so `my_dict` is not defined yet though you are defining it in this line. – lmiguelvargasf Feb 17 '17 at 01:40
  • @zwer how, exactly? – juanpa.arrivillaga Feb 17 '17 at 01:40
  • 1
    Split up the items being added so that they are defined before you try to back-reference them, like this (shown here on one line b/c Stack Overflow does not support formatting in Comments): my_dict = {} ; my_dict['key'] = 'value' ; my_dict['key1'] = 'value1' ; my_dict['key2'] = my_dict['key'] – rob_7cc Oct 26 '18 at 14:26

1 Answers1

6

Set the value of key2 to something phony (say, None), initialize my_dict properly, and then change the value of my_dict['key2'] to my_dict["key"].

DYZ
  • 55,249
  • 10
  • 64
  • 93