0 Daumen
480 Aufrufe


I want to iterate through two dictionaries in python one by one and always multiply the vales of one dictionary with the values of the other dictionary. I always want to multiply the value of the first item in dict 1 with the value of the first item in dict 2 and so on.

In this example I show what I have until now:

trial = {"a":1, "b":2, "c":3, "d":4}
trial2 = {"r":2, "t":3, "u": 4, "j": 5}

for y in trial.values():
    for z in trial2.values():
        mul = y * z

But now, it prints for the first value in dict 1 (1) 1 multiplied with every value of trial 2. And then the same with all the other values. But I only want: 1 * 2, 2 * 3, 3 * 4 and 4 * 5.

How can I specify this? Do you understand the question? Thanks!!


1 Antwort

+3 Daumen
Beste Antwort

You have to use an iterator.

This method is quite bad, as it will take a lot of time, but it works:

iterator = 0
iterator2 = 0
for y in trial.values():
iterator2 = iterator
for z in trial2.values():
if iterator2 != 0:
iterator -= 1
mul = y*z
iterator += 1

I hope this helps



Okay thanks a lot!

Haha well so what other options/tools are there that I could use? Because in the final tast I will be using a quite large data base (this was just an example). And I don‘t want my laptop to overload.

I'm not very familiar with python, therefore I will only explain how to do:

In order to iterate through a dictionary, you must have a list/array, which provides all the keys of the dictionary in right order. In youe example:

trial[] = {a, b, c, d} and trial2[] = {r, t, u, j}

At the time you're filling the dictionary also save the key in the array/list.

The dictionary (in my understanding) is like a hashtable and therefore has a really short access time. (Probably I am wrong, but then you habe to accept a long runtime)

Then iterate through both key-arrays and search for the values in the dictionaries and do whatever you want.

In case, you haven't initialized the dictionary yourself (what I think should not be the case, as no one would type dicrionary entries in an constructor/method) then you have to iterate through the second dictionary and get all the keys afterwards in your array/list.

Then iterate through the dictionary1 and through the array/list with the keys and search the value in dictionary2 with the current key at array/list index.

Just ask if you don't get it, probably I should write code, maybe later, when I'm awake...

Oh wow thanks a lot for your explanation! I think I can work with this, yes.

Ein anderes Problem?

Stell deine Frage

Ähnliche Fragen

Willkommen bei der Stacklounge! Stell deine Frage einfach und kostenlos

Made by a lovely community