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

28th Dec 2018, 12:59 AM
Matthew Grimalovsky
Matthew Grimalovsky - avatar
4 Answers
+ 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
28th Dec 2018, 10:53 AM
Kuba Siekierzyński
Kuba Siekierzyński - avatar
+ 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.
28th Dec 2018, 1:06 AM
HonFu
HonFu - avatar
+ 2
In addition to what HonFu said, you can do it like: for i in range(len(keys)) : storage[keys[i]] = values[i]
28th Dec 2018, 2:49 AM
Шащи Ранжан
Шащи Ранжан - avatar
+ 2
Thank you so much!
28th Dec 2018, 2:25 PM
Matthew Grimalovsky
Matthew Grimalovsky - avatar