ניסן פייגין
ניסן פייגין

Reputation: 43

extracting value from a "timestamp" labeled dictionery

Lets say I have this dictionry (using pandas timestamp):

d = {Timestamp('2020-06-30 00:00:00'): {'intangibleAssets': 295, 'capitalSurplus': 415},Timestamp('2020-03-30 00:00:00'): {'intangibleAssets': 400, 'capitalSurplus': 50}}

How can i exctarct a single value, like 295 located in d["Timestamp('2020-06-30 00:00:00')"]["intangibleAssets"]?

Thanks a lot!

Upvotes: 1

Views: 80

Answers (3)

Dishin H Goyani
Dishin H Goyani

Reputation: 7693

Use pd.Timestamp because our dictionary key type is pd.Timestamp not str.

import pandas as pd
d[pd.Timestamp('2020-06-30 00:00:00')]["intangibleAssets"]
295

Upvotes: 1

Vivs
Vivs

Reputation: 475

Below function is generic and can be implemented to any number of dictionary.
To get the keys:

def matchingKeys(dictionary, searchString):
    return [key for key,val in dictionary if searchString in val]

To get the values:

def matchingValues(dictionary, searchString):
    return [val for key,val in dictionary if searchString in val]

To get both:

def matchingElements(dictionary, searchString):
    return {key:val for key,val in dictionary if searchString in val}

Upvotes: 0

David Erickson
David Erickson

Reputation: 16683

Since you are using pandas, you can transform to a dataframe and use loc or .iloc passing the row and column that you are interested in:

with .loc:

d = {'2020-06-30 00:00:00': {'intangibleAssets': 295, 'capitalSurplus': 415},'2020-03-30 00:00:00': {'intangibleAssets': 400, 'capitalSurplus': 50}}
df = pd.DataFrame(d).loc['intangibleAssets','2020-06-30 00:00:00']
df
295

OR iloc:

d = {'2020-06-30 00:00:00': {'intangibleAssets': 295, 'capitalSurplus': 415},'2020-03-30 00:00:00': {'intangibleAssets': 400, 'capitalSurplus': 50}}
df = pd.DataFrame(d).iloc[0,0]
df
295

Upvotes: 0

Related Questions