1

I have this dictionary:

A = {"a": 1, "b":2}

And I want to write, instead of above initialization, a variable instead of 2 that is 4 times a's value that updates if a's value changes.

I cannot do this:

A={"a": 1, "b": 4*A["a"]}

How can I handle this?

‡: Here in my code,

flight = {
    "dest": "".join(random.choice(string.ascii_uppercase) for n in xrange(3)),
    "from": "".join(random.choice(string.ascii_uppercase) for n in xrange(3)),
    "not_available_seats": [],
    "available_seats": 50,
    "uid": uid,
    #"price": 10,
    "date": datetime.datetime.now()
}
flight["price"] = lambda: (51 - flight["available_seats"])*10

So when print flight(), I get error.

11
  • 5
    If I'm not mistaken, within the {} A doesn't exist yet, so A["a"] has no meaning. Commented Mar 2, 2018 at 21:40
  • 1
    Possible duplicate of Can you set a dictionary value dependant on another dictionary entry? Commented Mar 2, 2018 at 21:41
  • You edited the question, but now it's confusing. If you initialize A with static values, and then try to re-initialize it with a dynamic value (as reflected in your question), it will work fine. If you instead ONLY try to initialize it self-referentially, then it won't work (see @jpp's link). Commented Mar 2, 2018 at 21:42
  • Could you do two assignments? Ie A={"a": 1}; A["b"]=4*A["a"];. At this point, A exists, and contains a "a" key with a value. Commented Mar 2, 2018 at 21:43
  • 1
    @jpp I too smell an XY problem Commented Mar 2, 2018 at 21:52

2 Answers 2

3

Use a lambda function, then call A["b"] when you want the proper value:

>>> A={"a": 1}
>>> A["b"]= lambda: 4*A["a"]
>>> A["b"]()
4
>>> A["a"] = 5
>>> A["b"]()
20

Updated for the case where A["a"] is a list:

>>> A={"a": [1,2,3,4,5]}
>>> A["b"]= lambda: [4*i for i in A["a"]]
>>> A["b"]()
[4, 8, 12, 16, 20]
Sign up to request clarification or add additional context in comments.

2 Comments

The issue I have with this implementation is that while the syntax is nice ("just add () after a dictionary call"), in reality the dictionary isn't storing the value itself. It must recalculate each time. I posted an object-oriented solution which I believe better suits the problem.
@jpp Oh I agree, the overarching issue is best solved with an OOP solution. Definitely an XY problem. +1 to your approach!
1

The more I look at this problem the more I believe you want an object-oriented solution.

Here is one implementation:

import random, string
from datetime import datetime

class Flight(object):

    def __init__(self, dest, origin, not_available_seats, available_seats, uid, date):
        self.dest = dest
        self.origin = origin
        self.not_available_seats = not_available_seats
        self.available_seats = available_seats
        self.uid = uid
        self.date = date
        self.price = (51 - self.available_seats) * 10

    def set_available_seats(self, available_seats):
        self.available_seats = available_seats
        self.price = (51 - self.available_seats) * 10
        return None

You can create a class instance as easily as adding a dictionary item:

F1 = Flight("".join(random.choice(string.ascii_uppercase) for n in range(3)),
            "".join(random.choice(string.ascii_uppercase) for n in range(3)),
            [],
            50,
            123456789,
            datetime.now())

Updating available seats causes the price to update:

print(F1.price)              # 10
F1.set_available_seats(30)
print(F1.price)              # 210

1 Comment

Thanks, this is great and what I want!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.