Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Getting value using a key from a dictionary acts differently in 2 methods

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
>>>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading