Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dicts in Python

I have a multidimensionnal dict, I need to return a specific value.

ConsomRatio={"DAP_Local":[],"MAP11_52":[]}
ConsomRatio["DAP_Local"].append({"Ammonia":"0.229", "Amine":"0.0007"})
ConsomRatio["MAP11_52"].append({"Ammonia":"0.138", "Fuel":"0.003"})

print(ConsomRatio["DAP_Local"])

The result of the print is:

[{'Ammonia': '0.229', 'Amine': '0.0007'}]

My question is : Is there a way to return the value of "Ammonia" only, in "DAP_Local" ?

Thank you!

like image 952
AmyMagoria Avatar asked Feb 24 '15 17:02

AmyMagoria


2 Answers

You can get to it like this. You're appending your dict to a list, so you must select the correct index in the list where the dict is located. In this case the first element in the list or index 0.

ConsomRatio["DAP_Local"][0]["Ammonia"]

By the way, depending on what you are trying to achieve you might wanna take a look at the other answers for different implementations of multi-dimensional dicts.

like image 198
jramirez Avatar answered Sep 24 '22 02:09

jramirez


The other answers are of course correct, but have you considered using a "dict of dicts"? i.e.:

ConsomRatio={"DAP_Local":{},"MAP11_52":{}}
ConsomRatio["DAP_Local"].update({"Ammonia":"0.229", "Amine":"0.0007"})
ConsomRatio["MAP11_52"].update({"Ammonia":"0.138", "Fuel":"0.003"})

print ConsomRatio["DAP_Local"]["Ammonia"]
0.229
like image 44
Sigve Karolius Avatar answered Sep 25 '22 02:09

Sigve Karolius