Expanding on my comment, which is inspired by this answer to a different question (please upvote that one if you like this one):
You can assign the value of the key "time"
to be a lambda
function.
default=time.time()
a={"key":{"key_value":"value", "time": lambda: default}}
But if you were to print a
, you'd see this:
>>> print(a)
{'key': {'key_value': 'value', 'time': <function <lambda> at 0x7f39aa90cc08>}}
So, make a helper function to which will assign the current value of default
to the key "time"
when you want:
def get_my_dict(a, time_key="time"):
d = {}
d = {
k:(a[k]() if k == time_key else a[k])
if not isinstance(a[k], dict)
else get_my_dict(a[k]) for k in a
}
return d
In this case, I am using recursion to go through all nested dictionaries looking for the time_key
. If it is found, the function is called (notice the parentheses)- otherwise, the value is returned. You can simplify this based on your needs.
Now you can do the following:
>>> new_a = get_my_dict(a)
>>> print(new_a)
{'key': {'key_value': 'value', 'time': 1516979156.041796}}
If we subsequently update default
:
>>> default = 0
>>> new_a = get_my_dict(a)
>>> print(new_a)
{'key': {'key_value': 'value', 'time': 0}}
Update
If instead, you want the current time, simply change the lambda
function to time.time
:
a={"key":{"key_value":"value", "time": time.time}}
Note that there are no parentheses after time.time
. Everything else will work the same, except when you call get_my_dict(a)
, you will get the current time.
print(a)
{'key': {'key_value': 'value', 'time': <built-in function time>}}
new_a = mydict(a)
print(new_a)
{'key': {'key_value': 'value', 'time': 1516980015.325011}}
# wait a little and try again:
new_a = mydict(a)
print(new_a)
{'key': {'key_value': 'value', 'time': 1516980069.949716}}