+ 2

Set dict values

Is there a way I can set the dict values from a list for example if I have dict = {"a": 1, "b": 2} I would like to do something like dict.values = [3, 4] and it will become {"a": 3, "b": 4}

2nd Aug 2018, 5:04 PM
TheNewHEROBRINE
TheNewHEROBRINE - avatar
3 Antworten
+ 2
I think I found a better way: d = dict(zip(d, values))
2nd Aug 2018, 7:20 PM
TheNewHEROBRINE
TheNewHEROBRINE - avatar
+ 10
Mhm! example_dict = {} dict_key = [ "a", "b", "c" ] for i in range(3, 6): example_dict[dict_key[i]] = i print(example_dict) The example's ouput would be { 'a' : 3, 'b' : 4, 'c' : 5 } To get a value from a dictionary by using a pre-defined key, you would type the dictionary's variable name (example_dict), followed by brackets [ ], with the key inside of the braces. This will output/return whatever the key points to. You can define a dictionary in one line ... dict = { 'abc' : 123, 'sololearn' : 'is awesome' } ... or you can define it in such a way that is very similar to how you'd retrieve a value, except instead of simply doing something like example_dict["abc"], you also assign a value to it (like the example-code above does within the for-loop). I'm sure there are other ways as well, via the use of strategies oriented around generators, etc. Hope this helps.
2nd Aug 2018, 6:18 PM
Fox
Fox - avatar
+ 10
Lol. I was trying to show you in a way where you could visualize how it would be done with ease, but that works too I guess.
2nd Aug 2018, 11:04 PM
Fox
Fox - avatar