Lohengrin
Lohengrin

Reputation: 285

Can a Python dict item access other items of the same dict?

In Python, can we define a dict with items that depend on other items of the same dict, without using dict.update() or so in more than one step?

For example:

d = {
     key01 : d["key02"][0],
     key02 : [1.0,2.0,3.0]
    }

However, this gives:

NameError: name 'd' is not defined

Thanks a lot!

Upvotes: 1

Views: 452

Answers (1)

user1823
user1823

Reputation: 1111

When you are creating d, you expect d to already be created. Thus, it will not work. Instead, just reference the item earlier:

item = [1.0,2.0,3.0]
d = {
     key01 : item[0],
     key02 : item
    }

Upvotes: 4

Related Questions