简体   繁体   中英

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

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

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM