Given dictionaries, d1 and d2, create a new dictionary with the following property: for each entry (a, b) in d1, if a is not a key of d2 (i.e., not a in d2) then add (a,b) to the new dictionary for each entry (a, b) in d2, if a is not a key of d1 (i.e., not a in d1) then add (a,b) to the new dictionary For example, if d1 is {2:3, 8:19, 6:4, 5:12} and d2 is {2:5, 4:3, 3:9}, then the new dictionary should be {8:19, 6:4, 5:12, 4:3, 3:9} Associate the new dictionary with the variable d3

Done in Python please!

Here's what I have:

d3 = {}

for i,v in d1.items():

if v in d2.keys():
d3[i] = d2[v]

Respuesta :

Answer:

Python code explained below

Explanation:

# python code

import sys

import readline

from sys import stdin

import random

d1 = {2:3, 8:19, 6:4, 5:12}

d2 = {2:5, 4:3, 3:9}

d3 = {}

#for each entry (a, b) in d1

for i,v in d1.items():

  # if a is not a key of d2

  if i not in d2.keys():

      # add (a,b) to the new dictionary

      d3[i] = v

# for each entry (a, b) in d2

for i,v in d2.items():

  # if a is not a key of d1

  if i not in d1.keys():

      #add (a,b) to the new dictionary

      d3[i] = v

print "d3: ", d3

#output: d3: {8: 19, 3: 9, 4: 3, 5: 12, 6: 4}

Answer:

d1 = {2:3, 8:19, 6:4, 5:12}

d2 = {2:5, 4:3, 3:9}

d3 = {}

for key,value in d1.items():  

       if key not in d2.keys():

                   d3[key] = value

for key,value in d2.items():

        if key not in d1.keys():

                   d3[key] = value

print(d3)

Explanation:

The code is written in python as instructed from the question.

d1 = {2:3, 8:19, 6:4, 5:12}  This is the d1 dictionary entry with the key-value pair.

d2 = {2:5, 4:3, 3:9}   This is the d2 entry with the key-value pair.

d3 = {}  This is an empty dictionary to unpack values

for key,value in d1.items():  This code loops through dictionary d1 and get the key-value pair

if key not in d2.keys():  If any of key in d1 is not in d2 keys.

d3[key] = value  Then add the key-value pair to the empty d3

for key,value in d2.items():  This code loops through dictionary d2 and get the key-value pair

if key not in d1.keys():   If any of key in d2 is not in d1 keys

d3[key] = value  Then add the key-value pair to the empty d3

print(d3)  Display the final key-value pairs of d3