Home > Back-end >  Replace the keys of one dictionary with the values from another IF the keys of both dictionaries mat
Replace the keys of one dictionary with the values from another IF the keys of both dictionaries mat

Time:01-31

I have two dictionaries.

a = {3: 1, 14: 2, 4: 3, 1: 4, 5: 5, 16: 6, 2: 7, 6: 8, 15: 9, 10: 10, 7: 11, 9: 12, 8: 13, 12: 14, 13: 15, 11: 16} 
b = {1: 29, 2: 63, 3: 29, 4: 32, 5: 46, 6: 29, 7: 24, 8: 63, 9: 67, 10: 46, 11: 29, 12: 24, 13: 67, 14: 2, 15: 63, 16: 2, 17: 42}

I want to assign the values of a to the values of b if the keys match. Or some other similar result. I've been learning Python for about a week and I'm pretty sure the answer involves list comprehension but I just can't get my ahead around some of the other answers on here so a step by step for loop style answer would be much appreciated. Thanks

CodePudding user response:

Iterate over the set of keys in a and if that key exists in b, set b's value at that key to the value of a at that key

for key in a.keys():
    if key in b:
      b[key] = a[key]

Hope it helped

CodePudding user response:

You can loop the dict a.

Add a condition if a key exist in dict b

If they match, assign the dict b with key as the value from the dict a

for _a in a:
    if _a in b:
        b[_a] = a[_a]

CodePudding user response:

a = {3: 1, 14: 2, 4: 3, 1: 4, 5: 5, 16: 6, 2: 7, 6: 8, 15: 9, 10: 10, 7: 11, 9: 12, 8: 13, 12: 14, 13: 15, 11: 16} 
b = {1: 29, 2: 63, 3: 29, 4: 32, 5: 46, 6: 29, 7: 24, 8: 63, 9: 67, 10: 46, 11: 29, 12: 24, 13: 67, 14: 2, 15: 63, 16: 2, 17: 42}

a_list = list(a)
b_list = list(b)
for key in range(len(a_list)):
    if b_list[key] == a_list[key]:
        b[b_list[key]] = a[a_list[key]]


print(b)

outputs {1: 29, 2: 63, 3: 29, 4: 32, 5: 5, 6: 29, 7: 24, 8: 63, 9: 67, 10: 10, 11: 29, 12: 24, 13: 67, 14: 2, 15: 63, 16: 2, 17: 42}

not sure if this is the output you wanted

CodePudding user response:

In your example, the keys of a are a subset of the keys of b. If that's not just a bad example but always the case, you can just do b.update(a).

CodePudding user response:

a = {3: 1, 14: 2, 4: 3, 1: 4, 5: 5, 16: 6, 2: 7, 6: 8, 15: 9, 10: 10, 7: 11, 9: 12, 8: 13, 12: 14, 13: 15, 11: 16} 
b = {1: 29, 2: 63, 3: 29, 4: 32, 5: 46, 6: 29, 7: 24, 8: 63, 9: 67, 10: 46, 11: 29, 12: 24, 13: 67, 14: 2, 15: 63, 16: 2, 17: 42}

for key_a, value_a in a.items():
    for key_b, value_b in b.items():
        if(key_a == key_b):
            b[key_b] = value_a
print(b)

Output:

{1: 4, 2: 7, 3: 1, 4: 3, 5: 5, 6: 8, 7: 11, 8: 13, 9: 12, 10: 10, 11: 16, 12: 14, 13: 15, 14: 2, 15: 9, 16: 6, 17: 42}
  •  Tags:  
  • Related