0

thanks for helping me. I'm learning Python and I cannot make it work to have a response with all the info in a single dictionary by running two for loops.

See this example, if I run the loop like this...

mylist1 = ["image1", "image2", "image3"]
pictures_list = ["image1_url", "image2_url", "image3_url"]
mydict = {}
for item in mylist1:
    mydict['name'] = item
    for url in pictures_list:
        mydict['url'] = url
        print(mydict)

I have this answer, which iterates 3 times

{'name': 'image1', 'url': 'image1_url'}
{'name': 'image1', 'url': 'image2_url'}
{'name': 'image1', 'url': 'image3_url'}
{'name': 'image2', 'url': 'image1_url'}
{'name': 'image2', 'url': 'image2_url'}
{'name': 'image2', 'url': 'image3_url'}
{'name': 'image3', 'url': 'image1_url'}
{'name': 'image3', 'url': 'image2_url'}
{'name': 'image3', 'url': 'image3_url'}

If I remove one indentation to the print statement like this...

mylist1 = ["image1", "image2", "image3"]
pictures_list = ["image1_url", "image2_url", "image3_url"]
mydict = {}
for item in mylist1:
    mydict['name'] = item
    for url in pictures_list:
        mydict['url'] = url
    print(mydict)

I got one a single iteration to add the key but it doesn't iterate on the value assignment.

{'name': 'image1', 'url': 'image3_url'}
{'name': 'image2', 'url': 'image3_url'}   
{'name': 'image3', 'url': 'image3_url'}  

So I wonder how I could actually build the code to get an output like this

{'name': 'image1', 'url': 'image1_url'}
{'name': 'image2', 'url': 'image2_url'}   
{'name': 'image3', 'url': 'image3_url'}  
arkanjie
  • 53
  • 7

2 Answers2

2

zip will package both your lists into a single list where items with the same index in each list will be placed into a tuple:

print(list(zip(mylist1,pictures_list)))

Output:

[('image1', 'image1_url'), ('image2', 'image2_url'), ('image3', 'image3_url')]

Since a dict can take a list of tuples and convert them to a dictionary you can then use:

dictionary = dict(zip(mylist1,pictures_list))
print(dictionary)

Output:

{'image1': 'image1_url', 'image2': 'image2_url', 'image3': 'image3_url'}

Not only does this provide a concise, readable solution to your problem but it also has a time complexity of O(n) which is an improvement over your O(n**2) attempt.

thornejosh
  • 148
  • 8
0

something like the below

images = ["image1", "image2", "image3"]
urls = ["image1_url", "image2_url", "image3_url"]
data = [{'name': images[i], 'url': urls[i]} for i in range(len(images))]
print(data)

output

[{'name': 'image1', 'url': 'image1_url'}, {'name': 'image2', 'url': 'image2_url'}, {'name': 'image3', 'url': 'image3_url'}]
balderman
  • 22,927
  • 7
  • 34
  • 52