0

What I'd like to do is the following:

test_dict = dict(value = 1,
                 property = properties_list[value-1]
                )

Naturally, I couldn't do it this way, since it throws me an error saying that name 'value' is not defined.

Gabriel Dante
  • 392
  • 1
  • 12

2 Answers2

1

Since you can add keys after the dictionary is defined you could do

test_dict = dict(value = 1)
test_dict['property'] = properties_list[test_dict['value']-1]
jodag
  • 19,885
  • 5
  • 47
  • 66
1

You could do it by using an assignment expression (aka “the walrus operator”) which were introduced in Python 3.8.

properties_list = [42, 13]

test_dict = dict(value=(_:=1), property=properties_list[_-1])

print(test_dict)  # -> {'value': 1, 'property': 42}
martineau
  • 119,623
  • 25
  • 170
  • 301