Dictations in Python

I have a multi-disk 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"])

Print result:

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

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

Thank!

+4
source share
4 answers

Why are you putting lists in your dict like this? You can simply use dicts inside your main dict.

You can have multidimensional dicts also without lists, for example:

ConsomRatio = {}
ConsomRation["DAP_Local"] = {"Ammonia":"0.229", "Amine":"0.0007"}
ConsomRatio["MAP11_52"] = {"Ammonia":"0.138", "Fuel":"0.003"}

print(ConsomRatio["DAP_Local"]["Ammonia"])

will give the desired result without extra effort with the list.

In Python, you can get even shorter:

ConsomRatio = {
   "DAP_Local": {"Ammonia":"0.229", "Amine":"0.0007"},
   "MAP11_52" : {"Ammonia":"0.138", "Fuel":"0.003"},
}

print(ConsomRatio["DAP_Local"]["Ammonia"])

To answer your last question (in the second comment):

to_produce  = 'DAP_Local'
ingredience = 'Ammonia'
print('To produce {to_produce} we need {amount} of {ingredience}'.format(
      to_produce=to_produce, ingredience=ingredience,
      amount=ConsomRatio[to_produce].get(ingredience, '0.0')))

Hope this helps!

It gets even better:

for product, ingred_list in ConsomRatio.items(): 
    for iname, ivalue in ingred_list.items(): 
        print('To produce {to_produce} we need {amount} of {ingredience}'
              .format(to_produce=product, ingredience=iname, 
                      amount=ivalue))
+2
source

. dict list, list, dict. 0.

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

, , , .

+7

, , , "dict of dicts"? :.

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
+4

print(ConsomRatio["DAP_Local"]) 1, 0, "", .

print(ConsomRatio["DAP_Local"]) dict, [0] print(ConsomRatio["DAP_Local"]['Amomonia'])

+3

All Articles