Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I assign a value of a existing key in a dictionary?

I have to check if a key is in the dictionary or not. if it is there I have to assign at the variable the value of the key otherwise create a new key with a value for a raw_input. I write the code below but it doesn't work. I have to check if the key is in the dictionary or not.

For example I have a database of food recipe. "Oil" is almost in all recipes so i can't insert a raw_input for all a row of database. So I want to create a dictionary and select the value there.

For example in the database i have 100 row with ingredient "oil". I match this database with another. The key is the name of ingredient (in this case "oil") and the value is the characteristic (corn oil). Each row with the key "oil" must have the value "corn oil". Can i make this using a dictionary?

dict={}
for item in list:
#if the item is not in the list, I assign new value for a raw_input
    if dict.get(item) is None:
        dict[item]=value
    #if the item is in the list, I assing the previous value
    else:
        dict[item]=value

Can you help me, please? Thank you very much.

like image 985
kyle1009 Avatar asked Nov 08 '25 18:11

kyle1009


2 Answers

In my opinion, you always do dict[item] = value for any case, both if exists the item at the dictionary or not, then you have to create a new variable, for the dictionary, but I don't know that method you want to use, or what it will be the new key if the key already exists.

Sorry for my poor english if you don't understand something, write it!

like image 86
JuanB Avatar answered Nov 10 '25 08:11

JuanB


Item assignment will in both cases replace any existing value with the new one; there is no need to check if the key already exists.

d[key] = value
like image 20
Ignacio Vazquez-Abrams Avatar answered Nov 10 '25 08:11

Ignacio Vazquez-Abrams



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!