0

I have information I'm retrieving from a database:

with fields like

|Portfolio| Date | Sector| Industry | Ticker | Price | Postion|

and data like

("us", "2013-01", "Consumer","Retail","PM",10,1000)
("us", "2013-01", "Consumer", "Retail", "JCP", 15, 1500) ...

How can I turn this into a dictionary that looks like:

{us:{"2013-01":{"Consumer":{"Retail":{"PM":{"Price":10,"Position":1000},"JCP":{"Price":15, "Position":1500}}}}}}

in the most time and resource effective way?

something like

a[Date][Sector][Industry][Ticker].update("PM2" = dict(close=10, position = 1000))

gives me an error.

Thanks

5
  • What does the retrieved information look like? Commented Nov 19, 2014 at 14:20
  • 2
    Dont do this {us:{"2013-01":{"Consumer":{"Retail":{"PM":{"Price":10,"Position":1000},"JCP":{"Price":15, "Position":1500}}}}}} its not how dictionaries are meant to be used. Instead put all the key:value pairs in one {} bracket pair Commented Nov 19, 2014 at 14:21
  • 1
    I agree with @TimCastelijns, your example looks ugly, you should probably rethink your decision to use it like that. Commented Nov 19, 2014 at 14:23
  • Hi @TimCastelijns. Thanks for the comments. The reason I'm going with this approach is that in the final program I'll have multiple dates and I'll need to run calculations for each industry for each day. Some of those calculations will require aggregated numbers from each industry. I thought having hash key lookups would give me a performance advantage over multiple nested loops or filter requests. Is that incorrect? Commented Nov 20, 2014 at 1:37
  • Unless it makes your program run real slow, pick readability over performance. You know what you need best, though Commented Nov 20, 2014 at 7:57

1 Answer 1

1

You havent specified what error.

Anyways, this can be done by iterating each row and using the setdefault method dict, where you can check item and see if its already present in the dict.

So, for example -

a = {}
a.setdefault('us', {})
....
....
# if a now is 
# {'us':{"2013-01":{"Consumer":{"Retail":{"PM":{"Price":10,"Position":1000}}}}}}
# and you are iterating on 2nd row
a['us']['2013-01']['Consumer']['Retail'].setupdate('JCP', {})
.....

You may want to write a function for that. This is just an idea on how a better approach can be written.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.