Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Extract key1:value1 from dictionary 1 and key1:value1 from dictionary 2, assign them to 4 different variables, loop

What I need to do:

  • for each key in dictionary1 extract key1:value1 from dictionary1 and key1:value1 from dictionary2
  • assign those 2 pairs to 4 different variables
  • use those variables in other methods
  • move on to the next iteration (extract key2:value2 of both dictionaries 1 and 2, and assign to the same 4 variables)

Example:

d_one = {1:z, 2:x, 3:y}
d_two = {9:o, 8:n, 7:m}

the result has to be

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

a = 1
b = z
c = 9
d = o

(calling some other methods using those variables here)
(moving on to the next iteration)

a = 2
b = x
c = 8
d = n

(and so on)

My brain is overloaded on this one. Since I can’t nest for loops to accomplish this task, I guess the correct usage of ‘and’ statement should do it? I have no idea how so I try to split it up…

d_one = {'1':'z', '2':'x', '3':'y'}
d_two = {'9':'o', '8':'n', '7':'m'}

for i in range(0, len(d_one)):
    for a in list(d_one.keys())[i]:
        
        a = d_one.keys()[i]
        b = d_one[a]

    for c in list(d_two.keys())[i]:

        c = d_two.keys()[i]
        d = d_two[c]

    print(a, b, c, d)

output:

TypeError: 'dict_keys' object is not subscriptable

>Solution :

Try this:

d_one = {'1':'z', '2':'x', '3':'y'}
d_two = {'9':'o', '8':'n', '7':'m'}

for (a,b), (c,d) in zip(d_one.items(), d_two.items()):
    print(a, b, c, d)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading