Merging Two Dictionaries - but keep second values as priority

@ppr

Hi community

I am looking for an expression or a cleaner way to achieve this.

Scenario:
I have two dictionaries (both are String,Object). There may or may not be common Keys. I want to merge Dict1 => Dict2 but if the Key exists in Dict2 then skip that value.

Dict1
First: John
Last: Smith
Age: 40
Eye: Blue

Dict 2
Country: Australia
Vehicle: Yes
Age: 45

Final Dict2
First: John
Last: Smith
Age: 45 (common value but Dict2 value remains).
Eye: Blue
Country: Australia
Vehicle: Yes

Your suggestions are appreciated.

Cheers

Steve

Hi,

Can you share variable type of Dict1, Dict2 and Final Dict? And also what field is handled as key?

Regards,

All Dicts are (String,Object)

Edited top post also.

HI,

If we know which field is duplicated in advance (In the above case it’s “Age”), how about the following?

dictFinal = dict1.AsEnumerable.Where(Function(kv) kv.key<>"Age").Concat(dict2.AsEnumerable).ToDictionary(Function(kv) kv.Key, Function(kv)kv.Value)

Sample
Sample20240619-1.zip (2.7 KB)

Regards,

Thank you for the reply,

Unfortunately we won’t know the field/s.

HI,

All right, can you try the following?

dictFinal = dict1.AsEnumerable.Where(Function(kv) not dict2.Keys.Contains(kv.Key)).Concat(dict2.AsEnumerable).ToDictionary(Function(kv) kv.Key, Function(kv)kv.Value)

Sample
Sample20240619-1 (3).zip (2.7 KB)

Regards,

1 Like

Clean and clever way to reimagine the approach!

Love it @Yoichi !!

1 Like

That worked @Yoichi! :raised_hands: A true legend :man_superhero: in the UiPath community.

Thank you very much

Cheers

Steve

2 Likes

This topic was automatically closed 3 days after the last reply. New replies are no longer allowed.