Compare keys of dictionary with values of another dictionary

Allix

I have two dictionaries, both of type Dictionary<string, List<List<string>>. I want to select the range of entries from dictionary 1 which match the values/entries from dictionary 2.

E.g. dictionary 1 has the keys 01, 01.1 and dictionary 2 has the matching values 01, 01.1. at key 1

First I get the entries from dictionary 2 at key 1 like this:

var dictList = (from entry in DbDict
                where entry.Key == id.ToString() // id = 1
                select entry).ToList();

I tried to select these via linq with something like this:

var matchingEntries = (from entry in ExcelDict
                       where ExcelDict.Keys.Equals(dictList[0].Value)
                       select entry).ToList();

and tried more along those lines, but it won't return any results.

How do I get the range of valuepairs from dictionary 1, whose keys match the values of dictionary 2?

Edit1:

Dictionary 1: 
Key     Value
01      "these", "are"
        ..., ...
01.1    "just", "some"
        ..., ...
02      "sample", "values"
        ..., ...

Dictionary 2:
Key     Value
1       "01", "01.1"
        "foo", "bar"
        ..., ...                
2       "02", "02.21"
        "value1" "value2"

Edit2:

Expected output:

"01", "01.1"
"foo", "bar"

Edit3:

Compilable input as requested in the comments. This is exactly the structure I'm dealing with:

var dict1 = new Dictionary<string, List<List<string>>>();

dict1.Add("01", new List<List<string>> { new List<string> { "these" }, new List<string> { "are" } });
dict1.Add("01.1", new List<List<string>> { new List<string> { "just" }, new List<string> { "some" } });
dict1.Add("02", new List<List<string>> { new List<string> { "sample" }, new List<string> { "values" } });


var dict2 = new Dictionary<string, List<List<string>>>();
dict2.Add("1", new List<List<string>> { new List<string> { "01", "01.1" }, new List<string> { "foo", "bar" } });
dict2.Add("2", new List<List<string>> { new List<string> { "02", "value1" }, new List<string> { "02.21", "value2" } });

Edit4:

Sorry for the late response. Both Gaurang Dave's suggestion in the comments and the accepted answer worked for me. Thanks for everyone's help!

Harald Coppoolse

You wrote:

I want to select the range of entries from dictionary 1 which match the values/entries from dictionary 2.

From your output in Edit2, it seems that you want to take the values from Dictionary 2. You don't do anything with the Keys. Each value is a List<List<string>>. In your example all strings in the first list of the value with Key 1 have a corresponding key in dictionary 1. Apparently that is the condition to decide that the complete value is in your output.

The first list of the value with Key 2 has an element which is not a key in dictionary 1. Hence nothing of the value is in the output.

Unclear: what if the 2nd list would match instead of the 1st list?

Key     Value
3       "foo", "bar"
        "01", "01.1"

Should this also be in your final result?

Unclear Do you want as result a List<List<string>>, or do you want one big List<string> with all matching values? What about duplicate values?

Let's assume you only want to check the first List in your List of Lists:

We'll only look at the values from Dictionary 2, the keys are discarded. Then from every list in this value collection we take the first one (if there is one), and as a separate property remember the complete list.

Of course empty lists should not be in the end result, hence we keep only those that have a first element:

// Only use the values of dictionary 2:
IEnumerable<List<List<string>>> dict2Values = dictionary2.Values

// then for easy comparison extract the first list
var separatedFirstList = dict2Values.Select(listOfLists=> new
{
     FirstList = listOfLists.FirstOrDefault(), // this is a List<string> or null
     AllLists = listOfLists,    // original List<List<string>> where FirstList is the first
})

// keep only the elements that have a first list:
.Where(stringListWithFirstElement => stringListWithFirstElement.FirstList != null);

By now we have transformed your example dictionary into:

{
    FirstString = {"01", "01.1"},
    FullList =    {"01", "01.1"}, {"foo", "bar"}, {...}, {...},
},
{
    FirstString = {"02", "02.21"},
    FullList =    {"02", "02.21"}, {"value1" "value2"}, ...
},
{
     FirstString = ...,
     FullList = ...,
},
...

From this sequence we only want to keep those WHERE ALL elements in the FirstString are keys of Dictionary 1:

IEnumerable<string> keysDictionary1 = dictionary1.Keys;
var matchingItems = separatedFirstList
    .Where(item => item.FirstList.All(txt => keysDictionary1.Contains(txt));

You see the Where and the All.

Result:

{
    FirstString = {"01", "01.1"},
    FullList =    {"01", "01.1"}, {"foo", "bar"}, {...}, {...},
},
...

The one with FirstString = {"02", "02.21"} is removed, because not all elements of firstString where a Key in dictionary 1,

Finally: get rid of the FirstString:

List<List<String>> finalResult = matchingItems
    .Select(matchingItem => matchingItem.FullList);

Or if you want the result to be one List<String>:

List<string> finalResult = matchingItems.SelectMany(matchingItem => matchingItem.FullList);

TODO: consider creating one big LINQ statement. As the intermediate steps use lazy execution I'm not sure whether this will improve performance. However I'm sure that it will decrease readability.

この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。

侵害の場合は、連絡してください[email protected]

編集
0

コメントを追加

0

関連記事

分類Dev

Creating a dictionary with values identical to keys from another dictionary

分類Dev

Swap keys for values in dictionary?

分類Dev

Multiply values in a nested dictionary by values in another dictionary

分類Dev

How to match keys in a dictionary with the elements in a list and store those key values to another dictionary in python?

分類Dev

Assign list values to dictionary keys

分類Dev

Assigning values to keys in a mutable dictionary

分類Dev

Match keys to values in dictionary in python

分類Dev

Construct a dictionary from a list of dictionary keys, sub-keys and values

分類Dev

Filling a dataframe from a dictionary keys and values

分類Dev

retrieve values from dataframe using keys in dictionary

分類Dev

How to add multiple values to dictionary keys in Python

分類Dev

Edit nested dictionary duplicate values in same keys

分類Dev

How to sum up values of duplicate keys in a dictionary?

分類Dev

How can i change the values in a dictionary that are inside another dictionary?

分類Dev

How to get dictionary keys and values if both keys are in two separated dictionaries?

分類Dev

How can I return common values of dictionary values for specific keys?

分類Dev

Python Dictionary using Lists as Values, find other Keys with same values

分類Dev

How to write an excel file which has dictionary keys as column name and dictionary values as column values?

分類Dev

Check if a dictionary is subset of another dictionary

分類Dev

Trying to update a dictionary with another "dictionary"

分類Dev

Compare columns in a dictionary of dataframes

分類Dev

Compare columns in a dictionary of dataframes

分類Dev

Create dictionary from/with function arguments as keys and default values as value

分類Dev

Split Python dictionary into multiple keys, dividing the values equally

分類Dev

Search dictionary values and return List of keys meeting conditions

分類Dev

How to convert dictionary to dataframe when values of keys are list of list?

分類Dev

keep only keys without None values in dictionary from pandas groups

分類Dev

Make dictionary keys to be the same for common values of two different dictionaries

分類Dev

Read a JSON file and generate string keys with values in a dictionary like object

Related 関連記事

  1. 1

    Creating a dictionary with values identical to keys from another dictionary

  2. 2

    Swap keys for values in dictionary?

  3. 3

    Multiply values in a nested dictionary by values in another dictionary

  4. 4

    How to match keys in a dictionary with the elements in a list and store those key values to another dictionary in python?

  5. 5

    Assign list values to dictionary keys

  6. 6

    Assigning values to keys in a mutable dictionary

  7. 7

    Match keys to values in dictionary in python

  8. 8

    Construct a dictionary from a list of dictionary keys, sub-keys and values

  9. 9

    Filling a dataframe from a dictionary keys and values

  10. 10

    retrieve values from dataframe using keys in dictionary

  11. 11

    How to add multiple values to dictionary keys in Python

  12. 12

    Edit nested dictionary duplicate values in same keys

  13. 13

    How to sum up values of duplicate keys in a dictionary?

  14. 14

    How can i change the values in a dictionary that are inside another dictionary?

  15. 15

    How to get dictionary keys and values if both keys are in two separated dictionaries?

  16. 16

    How can I return common values of dictionary values for specific keys?

  17. 17

    Python Dictionary using Lists as Values, find other Keys with same values

  18. 18

    How to write an excel file which has dictionary keys as column name and dictionary values as column values?

  19. 19

    Check if a dictionary is subset of another dictionary

  20. 20

    Trying to update a dictionary with another "dictionary"

  21. 21

    Compare columns in a dictionary of dataframes

  22. 22

    Compare columns in a dictionary of dataframes

  23. 23

    Create dictionary from/with function arguments as keys and default values as value

  24. 24

    Split Python dictionary into multiple keys, dividing the values equally

  25. 25

    Search dictionary values and return List of keys meeting conditions

  26. 26

    How to convert dictionary to dataframe when values of keys are list of list?

  27. 27

    keep only keys without None values in dictionary from pandas groups

  28. 28

    Make dictionary keys to be the same for common values of two different dictionaries

  29. 29

    Read a JSON file and generate string keys with values in a dictionary like object

ホットタグ

アーカイブ