+ 1
Use of Dictionaries+Lists In Python
Hi, I am not new to python, however, I've never paid much attention to dictionaries as they did not serve any purpose in the programs I've had to create. I've recently been experimenting with them and I tried to make key/value combinations by looping through lists, and inputting them into a dictionary. My basic code: keys = ["Hello", "Goodbye"] values = [0, 1] storage = {} for i in keys: for j in values: storage[i] = j print(storage) However, the result is: {'Hello': 1, 'Goodbye': 1}
4 Respostas
+ 7
There is a much easier way of combining two lists (of same length) to a dictionary with them acting as keys and values, respectively.
Use zip() to join both tables in this way and dict() to convert it to a dicrionary:
https://code.sololearn.com/cn8Gmz35Nd4q/?ref=app
+ 4
You find the mistake if you play out your double loop step by step.
First key is 'Hello'.
Then in the inner loop, you assign first 0, then 1 to it.
Then you do the same with 'Goodbye'.
As a consequence both keys get the value 1.
+ 2
In addition to what HonFu said, you can do it like:
for i in range(len(keys)) :
storage[keys[i]] = values[i]
+ 2
Thank you so much!