1

I'm very new to learning Python and as part of trying to get more familiar with what it, I've been messing around with writing little bits of code that do things not explicitly taught in source I'm learning from but use the same concepts.

One thing that I was trying to do was have two lists, for example list=["apple", "banana", "orange", "grape"] and otherlist=["ok", "good", "better", "best"] and using them to create a dictionary where the end result was dict={"ok":"apple","good":"banana","better":"orange","best":"grape"}.

But I couldn't figure out how to do it. To my best understanding, I'd have to iterate through both lists sort of...in parallel so as to assign the first string in 'otherlist' as the key for the first string in 'list', and so on.

I tried doing some kind of for loop, as in

for word in otherlist:
    dict[word]=???

Where the "???" is where I get stuck, a since I can't figure out how to iterate through 'list' at the same time. Any help for this curious noob is appreciated! :)

Bob Bobby
  • 7
  • 2

3 Answers3

5

First of all avoid using the object types as variable names like list, you may either use a meaningful one or something like list1, list2, etc.

list1 = ["apple", "banana", "orange", "grape"]
list2 = ["ok", "good", "better", "best"]

In order to combined 2 lists (assuming to be of equal size) you may use zip and then cast the output to dict as :

d = dict(zip(list2, list1))
ZdaR
  • 22,343
  • 7
  • 66
  • 87
1
  1. Zip both lists together:

    list=["apple", "banana", "orange", "grape"]
    otherlist=["ok", "good", "better", "best"]
    zip(list, otherlist)
    [('apple', 'ok'), ('banana', 'good'), ('orange', 'better'), ('grape', 'best')]
    
  2. Call dict on the result to create a dictionary of these pairs.

    dict(zip(list, otherlist))
    {'orange': 'better', 'grape': 'best', 'apple': 'ok', 'banana': 'good'}
    

Note: You have to make sure that the elements of the first list are unique, otherwise the last element wins.

Hesham Attia
  • 979
  • 8
  • 13
0

try this:

mydict = dict()
for x in max(len(list), len(otherlist)):
    mydict[list[x]] = otherlist[x]
jath03
  • 2,029
  • 2
  • 14
  • 20