I have a dictionary of key:value pair in this format:
py_dict = {
"value": {
"Timestamp(" "2020-04-05 02:48:00" ")": 699.0,
"Timestamp(" "2020-06-26 07:36:00" ")": "nan",
"Timestamp(" "2020-06-26 08:40:00" ")": 699.0,
}
}
I am able to grab the key I need (latest timestamp) using datetime.strptime()
timestamps = {
datetime.strptime(key.strip('Timestamp("').strip('")'), "%Y-%m-%d %H:%M:%S"): value
for key, value in py_dict["value"].items()
if value != "nan"
}
# Find the maximum timestamp
latest_timestamp = max(timestamps)
# latest_timestamp returns <class 'datetime.datetime'> 2020-06-26 08:40:00
I convert the datetime object back to a string and format it to how the py_dict["value"] keys are structured
formatted_latest_timestamp_key = (
'Timestamp(" "' + latest_timestamp.strftime("%Y-%m-%d %H:%M:%S") + '" ")'
)
# returns <class 'str'> Timestamp(" "2020-06-26 08:40:00" ")
When I run the dict.get() method against the formatted_latest_timestamp_key I get none
latest_price = py_dict["value"].get(f'"{formatted_latest_timestamp_key}"')
# returns none
But if I run py_dict["value"].get() on the hardcoded key , I get the respective price.
My Python version:
home = /usr/bin
include-system-site-packages = false
version = 3.10.12
>Solution :
I believe you are confused about the actual key values in this subdictionary:
py_dict = {
"value": {
"Timestamp(" "2020-04-05 02:48:00" ")": 699.0,
"Timestamp(" "2020-06-26 07:36:00" ")": "nan",
"Timestamp(" "2020-06-26 08:40:00" ")": 699.0,
}
}
Looking at just the first key:
"Timestamp(" "2020-04-05 02:48:00" ")"
It is composed of three separate adjacent string literals:
Timestamp(
2020-04-05 02:48:00
)
When Python sees multiple adjacent string literals, they are joined together automatically. So the actual string key value is this:
Timestamp(2020-04-05 02:48:00)
It contains no double-quote characters, and only one space.
Here is a simplified example of this behavior:
>>> a = "hello" "there"
>>> print(a)
hellothere
>>>