Reputation: 67
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.
Upvotes: 1
Views: 88
Reputation: 164663
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
Upvotes: 1
Reputation: 51175
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]
Upvotes: 3