logo
down
shadow

Finding the intersection of two dictionaries


Finding the intersection of two dictionaries

By : caferosco
Date : November 22 2020, 10:33 AM
This might help you I have two dictionaries like Dic1 and Dic2 I want to generate a new list of the values for the keys that exist in both Dic1 and Dic2 So for example if , Here you are:
code :
var dic1 = new Dictionary<int, string> { { 12, "hi" }, { 14, "bye" } };
var dic2 = new Dictionary<int, string> { { 12, "hello" }, { 18, "bye" } };
HashSet<int> commonKeys = new HashSet<int>(dic1.Keys);
commonKeys.IntersectWith(dic2.Keys);
var result = 
    dic1
    .Where(x => commonKeys.Contains(x.Key))
    .Concat(dic2.Where(x => commonKeys.Contains(x.Key)))
    // .Select(x => x.Value) // With this additional select you'll get only the values.
    .ToList();
@EZI        Intersect2   GroupBy         ~149ms
@Selman22   Intersect3   Keys.Intersect   ~41ms
@dbc        Intersect4   Where1           ~22ms
@dbc        Intersect5   Where2           ~18ms
@dbc        Intersect5   Classic          ~11ms
@t3chb0t    Intersect1   HashSet          ~66ms
class Program
{
    static void Main(string[] args)
    {
        var dic1 = new Dictionary<int, string>();
        var dic2 = new Dictionary<int, string>();

        Random rnd = new Random(DateTime.Now.Millisecond);
        for (int i = 0; i < 100000; i++)
        {
            int id = 0;

            do { id = rnd.Next(0, 1000000); } while (dic1.ContainsKey(id));
            dic1.Add(id, "hi");

            do { id = rnd.Next(0, 1000000); } while (dic2.ContainsKey(id));
            dic2.Add(id, "hello");
        }

        List<List<string>> results = new List<List<string>>();

        using (new AutoStopwatch(true)) { results.Add(Intersect1(dic1, dic2)); }
        Console.WriteLine("Intersect1 elapsed in {0}ms (HashSet)", AutoStopwatch.Stopwatch.ElapsedMilliseconds);

        using (new AutoStopwatch(true)) { results.Add(Intersect2(dic1, dic2)); }
        Console.WriteLine("Intersect2 elapsed in {0}ms (GroupBy)", AutoStopwatch.Stopwatch.ElapsedMilliseconds);

        using (new AutoStopwatch(true)) { results.Add(Intersect3(dic1, dic2)); }
        Console.WriteLine("Intersect3 elapsed in {0}ms (Keys.Intersect)", AutoStopwatch.Stopwatch.ElapsedMilliseconds);

        using (new AutoStopwatch(true)) { results.Add(Intersect4(dic1, dic2)); }
        Console.WriteLine("Intersect4 elapsed in {0}ms (Where1)", AutoStopwatch.Stopwatch.ElapsedMilliseconds);

        using (new AutoStopwatch(true)) { results.Add(Intersect5(dic1, dic2)); }
        Console.WriteLine("Intersect5 elapsed in {0}ms (Where2)", AutoStopwatch.Stopwatch.ElapsedMilliseconds);

        using (new AutoStopwatch(true)) { results.Add(Intersect7(dic1, dic2)); }
        Console.WriteLine("Intersect7 elapsed in {0}ms (Old style :-)", AutoStopwatch.Stopwatch.ElapsedMilliseconds);

        Console.ReadKey();
    }

    static List<string> Intersect1(Dictionary<int, string> dic1, Dictionary<int, string> dic2)
    {
        HashSet<int> commonKeys = new HashSet<int>(dic1.Keys);
        commonKeys.IntersectWith(dic2.Keys);
        var result =
            dic1
            .Where(x => commonKeys.Contains(x.Key))
            .Concat(dic2.Where(x => commonKeys.Contains(x.Key)))
            .Select(x => x.Value)
            .ToList();
        return result;
    }

    static List<string> Intersect2(Dictionary<int, string> dic1, Dictionary<int, string> dic2)
    {
        var result = dic1.Concat(dic2)
                    .GroupBy(x => x.Key)
                    .Where(g => g.Count() > 1)
                    .SelectMany(g => g.Select(x => x.Value))
                    .ToList();
        return result;
    }

    static List<string> Intersect3(Dictionary<int, string> dic1, Dictionary<int, string> dic2)
    {
        var result =
            dic1
            .Keys
            .Intersect(dic2.Keys)
            .SelectMany(key => new[] { dic1[key], dic2[key] })
            .ToList();
        return result;
    }

    static List<string> Intersect4(Dictionary<int, string> dic1, Dictionary<int, string> dic2)
    {
        var result =
            dic1.
            Where(pair => dic2.ContainsKey(pair.Key))
            .SelectMany(pair => new[] { dic2[pair.Key], pair.Value }).ToList();
        return result;
    }

    static List<string> Intersect5(Dictionary<int, string> dic1, Dictionary<int, string> dic2)
    {
        var result =
            dic1
            .Keys
            .Where(dic2.ContainsKey).SelectMany(k => new[] { dic1[k], dic2[k] })
            .ToList();
        return result;
    }

    static List<string> Intersect7(Dictionary<int, string> dic1, Dictionary<int, string> dic2)
    {
        var list = new List<string>();
        foreach (var key in dic1.Keys)
        {
            if (dic2.ContainsKey(key))
            {
                list.Add(dic1[key]);
                list.Add(dic2[key]);
            }
        }
        return list;
    }
}

class AutoStopwatch : IDisposable
{
    public static readonly Stopwatch Stopwatch = new Stopwatch();

    public AutoStopwatch(bool start)
    {
        Stopwatch.Reset();
        if (start) Stopwatch.Start();
    }
    public void Dispose()
    {
        Stopwatch.Stop();
    }
}


Share : facebook icon twitter icon
Finding common ID's (intersection) in two dictionaries

Finding common ID's (intersection) in two dictionaries


By : 戚豪帅
Date : March 29 2020, 07:55 AM
To fix the issue you can do I wrote a piece of code that is supposed to find common intersecting ID's in line[1] in two different files. On my small sample files it works OK, but on my bigger files does not. I cannot figure out why, can you suggest me what is wrong? The exact problem is when my input is i.e. 200 it gives me 90 intersections, if I reduce it to 150, it gives me intersections of 110, logically it cannot be higher. , Pay attention to this:
code :
output.write(dictB[key][0]+'\t'+dictA[key][1]
for key in set(dictA).intersection(dictB):
for key in dictA:
   if key in dictB:
Intersection and Difference of two dictionaries

Intersection and Difference of two dictionaries


By : Ghecel Dagalea
Date : March 29 2020, 07:55 AM
this will help Here's one way of doing it, though there may be a more efficient method.
code :
d1 = {1:30, 2:20, 3:30, 5:80}
d2 = {1:40, 2:50, 3:60, 4:70, 6:90}

d_intersect = {} # Keys that appear in both dictionaries.
d_difference = {} # Unique keys that appear in only one dictionary.

# Get all keys from both dictionaries.
# Convert it into a set so that we don't loop through duplicate keys.
all_keys = set(d1.keys() + d2.keys()) # Python2.7
#all_keys = set(list(d1.keys()) + list(d2.keys())) # Python3.3

for key in all_keys:
    if key in d1 and key in d2:
        # If the key appears in both dictionaries, add both values
        # together and place it in intersect.
        d_intersect[key] = d1[key] + d2[key]
    else:
        # Otherwise find out the dictionary it comes from and place
        # it in difference.
        if key in d1:
            d_difference[key] = d1[key]
        else:
            d_difference[key] = d2[key]
Finding the intersection of a list of dictionaries based on an arbitrary field

Finding the intersection of a list of dictionaries based on an arbitrary field


By : Rami Kylä-Uuppo
Date : March 29 2020, 07:55 AM
like below fixes the issue Say I have a list of dictionaries l1 and l2. Each contains dictionaries of the same format. I'd like to find the intersection of l1 and l2 based on some field of the dictionary. , You can make this compact by using set comprehensions. For example,
code :
l1 = [{"key":1, "key2":2}, {"key":3, "key2":4}, {"key":5, "key2":6}, {"key":7, "key2":8}]
l2 = [{"key":0, "key2":2}, {"key":1, "key2":3}, {"key":2, "key2":4}]

key = "key2"
values = {d[key] for d in l1} & {d[key] for d in l2}
print(values)
{2, 4}
def key_set(seq, key):
    return {d[key] for d in seq}

values = key_set(l1, key) & key_set(l2, key)
all_lists = (l1, l2)
key = "key2"
values = set.intersection(*({d[key] for d in seq} for seq in all_lists))
Two dictionaries intersection C#

Two dictionaries intersection C#


By : R.Boojhawon
Date : March 29 2020, 07:55 AM
help you fix your problem I had two DateTime lists and was intersecting them with no problems: ,
The problem is that IEnumerable takes only DataTime lists
code :
public class AssetRecord: //IEquatable<AssetRecord> left as exercise
{   
    // Custom data type. Each object has time and price
    public DateTime AssetDate { get; set; } 
    public decimal AssetPrice { get; set; }

    public override bool Equals(object other)
    {
         if (other is AssetRecord)
         {
             var ass = (AssetRecord)other;
             return ass.AssetDate == AssetDate &&
                    ass.AssetPrice == AssetPrice;  
         }

         return false;
    }              

    public override int GetHashCode()
    {
        return AssetDate.GetHashCode() ^ AssetPrice.GetHashCode();
    }
}
What is the intersection of the keys of dictionaries

What is the intersection of the keys of dictionaries


By : deep aero
Date : March 29 2020, 07:55 AM
wish helps you filter, reduce, map, and lambda... oh my! This is Python, remember, so don't make this harder than it needs to be. Just using a good ol' for-loop:
code :
>>> keys, *morekeys = [d.keys() for d in Ld]
>>> for k in morekeys: 
...     keys &= k 
...
>>> keys
{1, 3}
>>> from functools import reduce
>>> from operator import and_
>>> reduce(and_, [d.keys() for d in Ld])
{1, 3}
Related Posts Related Posts :
  • Can we create and access a registry key in HKEY_LOCAL_MACHINE without running application with admin permissions in C#
  • Control light intensity with a UI slider
  • Threading (Does these threads exits or aborts itself?)
  • Change the function of a button if Logged in
  • how to accept value in date format in textbox in C# windows form?
  • remove the lines from RichtextBox?
  • How to call String.Split that takes string as separator?
  • Specify task timeout in parallel linq to objects
  • comparing two custom objects to prevent duplicates
  • How to Print Text from ComboBox into a MessageBox
  • How can I do a Func<object[],Expression<Func<T,bool>>> dynamic?
  • C# SqlDataReader No data exists for the row/column
  • My code is not giving the desired output
  • Is it possible to have multiple MVC routes point to the same controller/view?
  • Updating Listbox results in " Invalid cross-thread access."
  • Finding Elbow Angle with Kinect
  • Host a mvc web api application in the sub-folder of a website
  • How to generate a sequential unique id in a thread-safe way
  • How to add a separator to a WPF combobox that is databound?
  • optimize linq query with related entities
  • Optimize this code for large input
  • Is there any way to clear all list box short way?
  • ACR122 Device Programming sample does not find reader
  • Parallel Library: does a delay on one degree of parallelism delay all of them?
  • How to convert a var which contains Long to an Long[]
  • Quickly prune and create valid data combinations
  • Get 3 parameters out of a Dictionary<string, Dictionary<string Action>>
  • Regex IsMatch taking too long to execute
  • Shuffling divs using C# behindcode
  • ASP.NET Project and IE10 Compatibility Mode issues in Windows 7
  • Why can't I loop through this dictionary?
  • RavenDB Stream for Unbounded Results - Connection Resilience
  • How to remove the focus border of a CheckBox in C# Visual Studio?
  • Exception while using String.Format "Index (zero based) must be greater than or equal to zero and less than the siz
  • Caching an LDAP connection
  • C# How to detect kill event sender
  • How to Display Splashscreen and login form at same time using c#
  • Read .sql script with parameters
  • Why would I need to compile/generate methods/code at runtime?
  • Unable to create a constant value of type 'Project.Models.Subcategory'. Only primitive types or enumeration types are su
  • How to run possibly synchronous or possibly asynchronous code?
  • Drop SQLite tables using list of tables names
  • Can I organize Git submodules in a flat hierarchy?
  • How to make a server reply after receiving a request/data
  • Stored Procedure works in DB but not in C# code
  • MVVM WPF Programmatically add Child Elements
  • NCrunch and PostSharp Logging clash
  • Increasing memory usage in socket client
  • Multiple DropDownList but same action
  • How to get application memory usage as shown in Task Manager?
  • Exposing interfaces instead of concrete classes
  • How to get only postal_code data from google api?
  • Is there a way to get rid of the (by dot42) using community licence?
  • Why must I implement a function for an interface in vb.net which apparently doesn't need to be implemented in C#
  • How to remove HTML tags from the gridview Row
  • Get public post from Facebook's Graph Search API 2.x with Facebook SDK for .NET
  • C# DLL Export to Inno-Setup - Error E0434F4D
  • syntax error insert into database
  • By-pass else block of int.TryParse in Lambda Syntax
  • Retrieve "property getter" from the property name
  • shadow
    Privacy Policy - Terms - Contact Us © ourworld-yourmove.org