1

I'm trying to create a new dictionary based on an existing dictionary within the same class. Is it possible to reference one from field member in the declaration of another field member ? Does it require any special decorator for the first dict ?

class Foo:

    dict1 = {"a": 1, "b": 2, "c": 3} 

    dict2 = {i: Foo.dict1[i] * 10 for i in Foo.dict1}

print(Foo.dict2)
MD Luffy
  • 536
  • 6
  • 18
  • Possible duplicate of [Accessing class variables from a list comprehension in the class definition](https://stackoverflow.com/questions/13905741/accessing-class-variables-from-a-list-comprehension-in-the-class-definition) – sanyassh May 14 '19 at 11:48

3 Answers3

1

A simple solution is to add the second static member just after the definition of the class:

class Foo:
    dict1 = {"a": 1, "b": 2, "c": 3} 

Foo.dict2 = {i: Foo.dict1[i] * 10 for i in Foo.dict1}

print(Foo.dict2)
Serge Ballesta
  • 143,923
  • 11
  • 122
  • 252
0

You cannot do that directly because Foo is not defined at the time when dict2 is evaluated. It is easy enough work around that though:

class Foo:
    dict1 = {"a": 1, "b": 2, "c": 3} 
    _dict2 = None
    @staticmethod
    def dict2():
        if Foo._dict2 is None:
            Foo._dict2 = {i: Foo.dict1[i] * 10 for i in Foo.dict1}
        return Foo._dict2

print(Foo.dict2())
# {'a': 10, 'b': 20, 'c': 30}
jdehesa
  • 58,456
  • 7
  • 77
  • 121
0

I figured out a simpler solution. The trick is to use .items(), which returns the key,value tuple that can be referenced in the new dict.

class Foo:
    dict1 = {"a": 1, "b": 2, "c": 3} 
    dict2 = {itm[0]: itm[1] * 10 for itm in dict1.items()}

>>>Foo.dict2
{'a': 10, 'b': 20, 'c': 30}
MD Luffy
  • 536
  • 6
  • 18